I have simple bash script that starts lots of processes. If one fails I want to stop everything. There maybe a better way to do this but I came up with this.
First create two scripts to test our main script. good_sleep
that sleeps for 10 seconds and exits with no error.
#!/bin/bash
echo " good sleeping"
sleep 10
echo "done"
And bad_sleep
that exits with an error after 2 seconds
#!/bin/bash
echo "bad sleeping"
sleep 2
echo "throw error"
exit 1
In bash I could have used wait
to pause, but it waits until all the processes have finished. I want to stop things after the first process finishes. So I recored each PID in an array and poll this to see if they are still alive as follows.
#!/bin/bash
function error_finish {
echo "Error. Stopping all subprocesses"
kill 0
}
#trap exit and redirect to our command
trap error_finish EXIT
# start each process and record its PID into an array
./good_sleep &
pid[0]=$!
./bad_sleep &
pid[1]=$!
num_pids=${#pid[@]}
echo "Running $num_pids processes"
while true ; do
# loop over the pid array and test if the process is still
# alive. If not stop everything
for i in "${pid[@]}"
do
if ! ps -p $i > /dev/null;
then
echo "Stopped"
exit 1
fi
done
sleep 1
done