What's the best way to send a signal to all me

2018-12-31 07:58发布

I 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.

30条回答
梦醉为红颜
2楼-- · 2018-12-31 08:45

rkill command from pslist package sends given signal (or SIGTERM by default) to specified process and all its descendants:

rkill [-SIG] pid/name...
查看更多
素衣白纱
3楼-- · 2018-12-31 08:46

To kill a process tree recursively, use killtree():

#!/bin/bash

killtree() {
    local _pid=$1
    local _sig=${2:--TERM}
    kill -stop ${_pid} # needed to stop quickly forking parent from producing children between child killing and parent killing
    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 $@
查看更多
只靠听说
4楼-- · 2018-12-31 08:47

Modified version of zhigang's answer:

#!/usr/bin/env bash
set -eu

killtree() {
    local pid
    for pid; do
        kill -stop $pid
        local cpid
        for cpid in $(pgrep -P $pid); do
            killtree $cpid
        done
        kill $pid
        kill -cont $pid
        wait $pid 2>/dev/null || true
   done
}

cpids() {
    local pid=$1 options=${2:-} space=${3:-}
    local cpid
    for cpid in $(pgrep -P $pid); do
        echo "$space$cpid"
        if [[ "${options/a/}" != "$options" ]]; then
            cpids $cpid "$options" "$space  "
        fi
    done
}

while true; do sleep 1; done &
cpid=$!
for i in $(seq 1 2); do
    cpids $$ a
    sleep 1
done
killtree $cpid
echo ---
cpids $$ a
查看更多
永恒的永恒
5楼-- · 2018-12-31 08:47

I know that is old, but that is the better solution that i found:

killtree() { 
    for p in $(pstree -p $1 | grep -o "([[:digit:]]*)" |grep -o "[[:digit:]]*" | tac);do
        echo Terminating: $p 
        kill $p
    done
}
查看更多
与风俱净
6楼-- · 2018-12-31 08:48

brad's answer is what I'd recommend 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
查看更多
时光乱了年华
7楼-- · 2018-12-31 08:48

It's super easy to do this with python using psutil. Just install psutil with pip and then you have a full suite of process manipulation tools:

def killChildren(pid):
    parent = psutil.Process(pid)
    for child in parent.get_children(True):
        if child.is_running():
            child.terminate()
查看更多
登录 后发表回答