I basically want to kill a whole process tree. What is the best way to do this using any common scripting languages. I am looking for a simple solution.
Since you say you can use any common scripting languages, you could take a look at this question: How can I kill a whole process tree with Perl?
if you know pass the pid of the parent process, here's a shell script that should work:
for child in $(ps -o pid,ppid -ax | \
awk "{ if ( \$2 == $pid ) { print \$1 }}")
do
echo "Killing child process $child because ppid = $pid"
kill $child
done
brad's answer is what I'd recomment too, except that you can do away with awk altogether if you use the --ppid option to ps.
for child in $(ps -o pid -ax --ppid $PPID) do ....... done
You don't say if the tree you want to kill is a single process group. (This is often the case if the tree is the result of forking from a server start or a shell command line.) You can discover process groups using GNU ps as follows:
ps x -o "%p %r %y %x %c "
If it is a process group you want to kill, just use the kill(1)
command but instead of giving it a process number, give it the negation of the group number. For example to kill every process in group 5112, use kill -TERM -5112
.
Thanks for your wisdom, folks. My script was leaving some child processes on exit and the negation tip made things easier. I wrote this function to be used in other scripts if necessary:
# kill my group's subprocesses: killGroup
# kill also myself: killGroup -x
# kill another group's subprocesses: killGroup N
# kill that group all: killGroup -x N
# N: PID of the main process (= process group ID).
function killGroup () {
local prid mainpid
case $1 in
-x) [ -n "$2" ] && kill -9 -$2 || kill -9 -$$ ;;
"") mainpid=$$ ;;
*) mainpid=$1 ;;
esac
prid=$(ps ax -o pid,pgid | grep $mainpid)
prid=${prid//$mainpid/}
kill -9 $prid 2>/dev/null
return
}
Cheers.
To kill a process tree recursively, use killtree.sh:
#!/bin/bash
killtree() {
local _pid=$1
local _sig=${2-TERM}
for _child in $(ps -o pid --no-headers --ppid ${_pid}); do
killtree ${_child} ${_sig}
done
kill -${_sig} ${_pid}
}
if [ $# -eq 0 -o $# -gt 2 ]; then
echo "Usage: $(basename $0) <pid> [signal]"
exit 1
fi
killtree $@
if you have pstree and perl on your system, you can try this:
perl -e 'kill 9, (`pstree -p PID` =~ m/\((\d+)\)/sg)'