Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill all subprocesses of shell?

People also ask

How can I kill all descendants of a process?

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 .

Does killing a process kill all child processes?

Killing a parent doesn't kill the child processes Every process has a parent. We can observe this with pstree or the ps utility. The ps command displays the PID (id of the process), and the PPID (parent ID of the process).

How do you kill a process tree?

If you select the process at the top of the tree you want kill, then press F9 followed by Enter it will close the process and the entire process tree in one go.


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


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.


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

kill -- -1234


Extending pihentagy's answer to recursively kill all descendants (not just children):

kill_descendant_processes() {
    local pid="$1"
    local and_self="${2:-false}"
    if children="$(pgrep -P "$pid")"; then
        for child in $children; do
            kill_descendant_processes "$child" true
        done
    fi
    if [[ "$and_self" == true ]]; then
        kill -9 "$pid"
    fi
}

Now

kill_descendant_processes $$

will kill descedants of the current script/shell.

(Tested on Mac OS 10.9.5. Only depends on pgrep and kill)