How to kill all subprocesses of shell?

六月ゝ 毕业季﹏ 提交于 2019-11-27 20:01:19

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.

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

Dennis Williamson

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

kill -- -1234

Jürgen Hötzel
kill $(jobs -p)

Rhys Ulerich's suggestion:

Caveat a race condition, using [code below] accomplishes what Jürgen suggested without causing an error when no jobs exist

[[ -z "$(jobs -p)" ]] || kill $(jobs -p)

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)

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!