2012年1月31日星期二

Kill parent and child process

No, child processes are not necessarily killed when the parent is killed. On UNIX, there is no enforced relation between parent and child process's lifetimes. Process will only terminate when it calls exit() or receives unhandled signal for which default action is to terminate.

Exceptions:
1. If the child has a pipe open which it is writing to and the parent is reading from, it will get a SIGPIPE when it next tries to write to the pipe, for which the default action is to kill it. That is often what happens in practice.

2. Entire "foreground process group" in a "controlling terminal" can receive SIGINT, SIGQUIT, etc. signals when user hits ctrl-C, ctrl-\, etc. on that terminal. Specific behaviour is partly implemented by login shell (with help from tty driver), details may be quite complicated: look here and here





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.
 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 $@

 

没有评论: