views:

259

answers:

4

I'm writing bash script, which does several thing.

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 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?

+2  A: 

After starting each child process, you can get its id with

ID=$!

Then you can use the stored PIDs to find and kill all grandchild etc. processes as described here or here.

Péter Török
Just to add, if the monitors' subprocesses can spawn subsubprocesses etc., you'd need to use the technique described in the link recursively.
David Zaslavsky
@David the 2nd page referred includes a solution for that.
Péter Török
Yes, but that second link hadn't yet appeared when I wrote my comment.
David Zaslavsky
@David I thought so too. I didn't mean to counterargument or anything, sorry if it sounded like that.
Péter Török
Not to worry, it didn't :-) (by the way: +1)
David Zaslavsky
+1  A: 
kill $(jobs -p)
Jürgen Hötzel
+1  A: 

If you use a negative PID with kill it will kill a process group.

Dennis Williamson
+1  A: 

pkill with optioin "-P" should help:

pkill -P $(pgrep some_monitor1.sh)

from man page:

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

There are some discussions on linuxquests.org, please check:

http://www.linuxquestions.org/questions/programming-9/use-only-one-kill-to-kill-father-and-child-processes-665753/

ybyygu