Skip to content

Instantly share code, notes, and snippets.

@jbayer
Last active January 2, 2016 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbayer/8368233 to your computer and use it in GitHub Desktop.
Save jbayer/8368233 to your computer and use it in GitHub Desktop.
starts multiple processes and checks every second if each of them are alive, exiting the parent when any of the children exit
#!/bin/bash
function startChildProcesses
{
for cmd in "$@"; do {
$cmd & pid=$!
echo "Process \"$cmd\" started with pid $pid";
PID_LIST+=" $pid";
} done
PID_ARRAY=($PID_LIST)
}
function signalChildren {
for var in "${PID_ARRAY[@]}"
do
if ps -p $var > /dev/null
then
echo "sending $1 to $var"
kill -s $1 $var
fi
done
}
function exitAllOnAnyChildExit
{
while :
do
for var in "${PID_ARRAY[@]}"
do
if ps -p $var > /dev/null
then
:
else
echo "child process $var exited, killing all children and exiting"
signalChildren TERM
sleep 2
signalChildren KILL
exit 0
fi
done
sleep 1
done
}
startChildProcesses "$@"
exitAllOnAnyChildExit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment