Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to spawn processes, terminate children on SIGTERM

I want to write a shell script that spawns several long-running processes in the background, then hangs around. Upon receiving SIGTERM, I want all the subprocesses to terminate as well.

Basically, I want a "master process".

Here's what I got so far:

#!/bin/sh

sleep 600 &
PID1="$!"

sleep 600 &
PID2="$!"

# supposedly this should kill the child processes on SIGTERM. 
trap "kill $PID1 $PID2" SIGTERM 

wait

The above script fails with trap: 10: SIGTERM: bad trap.

Edit: I'm using Ubuntu 9.04

like image 829
itsadok Avatar asked Jun 10 '09 14:06

itsadok


2 Answers

This works for me:

trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
  • kill -- -$$ sends a SIGTERM to the whole process group, thus killing also descendants.

  • Specifying signal EXIT is useful when using set -e (more details here).

like image 177
tokland Avatar answered Oct 05 '22 08:10

tokland


Joe's answer put me on the right track. I also found out I should trap more signals to cover my bases.

Final script looks like this:

#!/bin/sh

sleep 600 &
PID1="$!"

sleep 600 &
PID2="$!"

trap "kill $PID1 $PID2" exit INT TERM

wait
like image 27
itsadok Avatar answered Oct 05 '22 07:10

itsadok