views:

60

answers:

2

How can I start serval applications in one script and pipe the output to current terminal?

For development I need a script which starts three webservers (on three ports, of course) and pipe the output of these to current terminal.

The difficult is to stop these webservers at the end of shell. I have to send a signal or better send [Ctrl + C] to all webservers.

I hope you're understanding me ;-)

+2  A: 

EDIT

#!/bin/bash
netstat &
p1=$!
netstat &
p2=$!
netstat &
p3=$!
trap "kill $p1 $p2 $p3" SIGINT
wait $p1 $p2 $p3

Script starts the other processes in the background and remembers their process IDs. It then waits for all of them to terminate. In the meantime, upon receiving a SIGINT (i.e. a ^C), it will kill those processes, which will then terminate the script too (for lack of more stuff to do). So by ^C'ing your script, you can kill all the background server processes.

Oh yeah... I'm using netstat as a long-running test command. Substitute whatever you want to run.

Finally, you can choose which signal to send your processes with kill. Check man kill for options; I think INT (the equivalent of ^C) is the default.

Carl Smotricz
Tried for a general, elegant solution... this is it. Conforms completely to the spec, right? ;)
Carl Smotricz
Yeah, this is it :-)
Sven Walter
Don't use `function` keyword: it is unnecessary, not portable and its consequences are undefined.
Roman Cheplyaka
In view of the `bash` tag, I felt well justified to use it. I'd be unhappy to remove it because it makes purpose of that line much easier to understand. Can you suggest a rewrite that does away altogether with the use of a function?
Carl Smotricz
Carl: answering your last question, `trap "kill $p1 $p2 $p3" INT` would be just as good. Even better -- it would protect you from modified p1, p2, p3 variable. (But I'm no way opposed to using functions in general -- just asking using the right syntax.)
Roman Cheplyaka
Thanks, updated to use your suggested syntax. Shorter = better.
Carl Smotricz
+1  A: 
web_server_1 &
ws1=$!
web_server_2 &
ws2=$!
web_server_3 &
ws3=$!
# Kill some time
kill -s SIGINT $ws1 $ws2 $ws3
Ignacio Vazquez-Abrams