q-ovnw
Last Updated: July 14, 2016
·
13.06K
· fish

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

1 Response
Add your response

22316

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 ·