January 2013
Kill all your children from a script
I had a script that ran debmirror, which in turn spawns multiple rsyncs, roughly like this:
#~/bin/bash
debmirror ...parameters... &
CHILDPID=$!
wait
When I killed that script, it would stop, but the rsyncs would continue to run. First thing to do then is to listen for signals and kill all children when they come in:
#~/bin/bash
debmirror ...parameters... &
trap "kill ${CHILDPID}" SIGHUP SIGQUIT SIGINT SIGTERM
CHILDPID=$!
wait
trap - SIGHUP SIGQUIT SIGINT SIGTERM
But then still, some rsyncs would still keep running.
Now I can of course use ps to find all debmirror's children, and kill each separately. But there's a nicer way, namely to start debmirror as a session leader with its own session group id, and kill the entire group:
#!/bin/bash
setsid debmirror ...parameters... &
CHILDPID=$!
trap "echo 'Signal received, killing children before dying' ; sesskill ${CHILDPID}" SIGHUP SIGQUIT SIGINT SIGTERM
wait
trap - SIGHUP SIGQUIT SIGINT SIGTERM