I'm trying to launch a couple of sub-programs from a bash script and then wait on either of them to quit before quitting the other and exiting the script.
CMD1PID= CMD2PID= exit_trap () { echo "exit trap: killing jobs..." sudo kill $CMD1PID $CMD2PID exit } set -bm trap exit_trap EXIT INT TERM sudo cmd1 --args & CMD1PID=$? sudo cmd2 --args & CMD2PID=$? wait $CMD1PID $CMD2PID
(For reference, this is GNU bash, version 4.2.37(1)-release (arm-unknown-linux-gnueabi)
on Debian Weezy)
Unfortunately, this doesn't seem to work properly. I've tried several variants, such as:
- using curly braces around the commands and explicitly killing the shell process afterwards, ie
{ cmd1 --args ; kill -USR1 $$ ; } &
or similar, and then trapping on USR1 - using
kill 0
to kill the still-running commands at exit - trapping
CHLD
- this has the disadvantage that I can'tsleep
between the commands if I need to, which I might eventually need to do.
...but the issues I tend to run into are:
- Killing one of the commands doesn't cause the parent Bash process to exit and/or kill the other command
- Killing the parent Bash process doesn't cause both commands to be killed
I suspect that perhaps my requirement to use sudo is tripping me up, as other folks in other scripts seem to be having good luck with similar scripts. Is there a good way of doing what I'm trying to do in bash?
sleep $n & wait
instead of simplysleep $n