Killing all child processes in a shell script
I wrote a shell script starting some background processes and needed to make sure to kill them all on exit. Turns that, that isn't as easy as one might expect. This is what I ended up doing:
First you need to trap some signals to execute a shutdown function. In that function we first need to get our process group id, then kill the complete process group in a new process group so we won't risk killing our selves:
#!/bin/bash
shutdown() {
# Get our process group id
PGID=$(ps -o pgid= $$ | grep -o [0-9]*)
# Kill it in a new new process group
setsid kill -- -$PGID
exit 0
}
trap "shutdown" SIGINT SIGTERM
... # start gazillion of background processes here
Written by Johannes 'fish' Ziemke
Related protips
1 Response
How did you come up with this? In other words: where did you find this solution?
Thank you very much for posting this.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Job control
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#