Bash Script – Interrupt Child Processes on Ctrl+C

bashinterruptlinuxprocess

I'm starting two child processes from bash script and waiting both for completion using wait command:

./proc1 &
pid1=$!
echo "started proc1: ${pid1}"

./proc2 &
pid2=$!
echo "started proc2: ${pid2}"

echo -n "working..."
wait $pid1 $pid2
echo " done"

This script is working fine in normal case: it's waiting both processes for completion and exit after it. But sometimes I need to stop this script (using Ctrl+C). But when I stop it, child processes are not interrupted. How can I kill them altogether with main script?

Best Answer

Set-up a trap handling SIGINT (Ctrl+C). In your case that would be something like:

trap "kill -2 $pid1 $pid2" SIGINT

Just place it before the wait command.

Related Question