7

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?

g4s8
  • 478

1 Answers1

14

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.

MAQ
  • 980
  • 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 ;-) –  Oct 11 '19 at 20:32
  • 1
    @DavyM good point. I changed the answer! – MAQ Oct 14 '19 at 12:20
  • @mosvy reset it then, 'trap - INT' – user2497 Nov 08 '19 at 16:55