In a Bash script, I would like to do something like:
app1 &
pidApp1=$!
app2 &
pidApp2=$1
timeout 60 wait $pidApp1 $pidApp2
kill -9 $pidApp1 $pidApp2
Here's a simplified version of Aaron Digulla's answer, which uses the kill -0
trick that Aaron Digulla leaves in a comment:
app &
pidApp=$!
( sleep 60 ; echo 'timeout'; kill $pidApp ) &
killerPid=$!
wait $pidApp
kill -0 $killerPid && kill $killerPid
In my case, I wanted to be both set -e -x
safe and return the status code, so I used:
set -e -x
app &
pidApp=$!
( sleep 45 ; echo 'timeout'; kill $pidApp ) &
killerPid=$!
wait $pidApp
status=$?
(kill -0 $killerPid && kill $killerPid) || true
exit $status
An exit status of 143 indicates SIGTERM, almost certainly from our timeout.