Interrupt child processes from bash script on Ctrl+C

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

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

./proc2 &
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?

Asked By: g4s8


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.

Answered By: MAQ
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.