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?
If you use a negative PID with
kill
it will kill a process group. Example:kill -- -1234
will fit (just kills it's own descendants)
EDIT: I got a downvote, don't know why. Anyway here is the help of -P
and
$$
is the process id of the script itselfExtending pihentagy's answer to recursively kill all descendants (not just children):
Now
will kill descedants of the current script/shell.
(Tested on Mac OS 10.9.5. Only depends on pgrep and kill)
Rhys Ulerich's suggestion:
pkill with optioin "-P" should help:
from man page:
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/
After starting each child process, you can get its id with
Then you can use the stored PIDs to find and kill all grandchild etc. processes as described here or here.