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?

1 Answer 1


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.

  • 1
    @DavyM also, the script is also supposed to reset the trap and kill itself with the same signal because of "Wait and Cooperative Exit" (see the links from here and here), and there's also the problem with the pids being possibly reused by the time of the kill (because the shell is actually reaping the children as soon as they terminate, before the wait built-in call). But fixing all that is probably over-engineering ;-)
    – user313992
    Oct 11, 2019 at 20:32
  • 1
    @DavyM good point. I changed the answer!
    – MAQ
    Oct 14, 2019 at 12:20
  • @mosvy reset it then, 'trap - INT'
    – user2497
    Nov 8, 2019 at 16:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .