Consider this code:
job()
{
local id=$1
sleep $id
}
do_job_in_parallel()
{
local pids=()
# run subshells
for id in $(seq 4)
do
job $id &
pids=("${pids[@]}" $!)
done
# wait subshells
for ((i=0; i<${#pids[@]}; ++i))
do
local pid=${pids[$i]}
wait $pid
exit_status=$?
if [[ $exit_status -ne 0 ]]
then
echo "job with pid $pid failed with exit status $exit_status"
#TODO: kill all subshells
fi
done
}
Consider that we need to implement "if any subshell failed, then all subshells failed" logic. If waiting of X and Y is done sequentially (as in the code above) AND if, for example, Y failed while waiting of X, then there is no need to wait X. How to implement, more precisely, "if any subshell failed, then kill immediately all other subshells"?