How to kill all subprocesses of shell?

user80168 picture user80168 · Apr 11, 2010 · Viewed 53.7k times · Source

I'm writing a bash script, which does several things.

In the beginning it starts several monitor scripts, each of them runs some other tools.

At the end of my main script, I would like to kill all things that were spawned from my shell.

So, it might looks like this:

#!/bin/bash

some_monitor1.sh &
some_monitor2.sh &
some_monitor3.sh &

do_some_work
...

kill_subprocesses

The thing is that most of these monitors spawn their own subprocesses, so doing (for example): killall some_monitor1.sh will not always help.

Any other way to handle this situation?

Answer

pihentagy picture pihentagy · Jul 12, 2013
pkill -P $$

will fit (just kills it's own descendants)

EDIT: I got a downvote, don't know why. Anyway here is the help of -P

   -P, --parent ppid,...
          Only match processes whose parent process ID is listed.

and $$ is the process id of the script itself