我想杀死整个进程树。使用通用脚本语言实现这一目标的最佳方法是什么?我在寻找一个简单的解决办法。


当前回答

为了补充Norman Ramsey的答案,如果您想创建一个流程组,可能值得看看setsid。 http://pubs.opengroup.org/onlinepubs/009695399/functions/setsid.html

The setsid() function shall create a new session, if the calling process is not a process group leader. Upon return the calling process shall be the session leader of this new session, shall be the process group leader of a new process group, and shall have no controlling terminal. The process group ID of the calling process shall be set equal to the process ID of the calling process. The calling process shall be the only process in the new process group and the only process in the new session.

我的意思是你可以从头开始创建一个组。我在php中使用这个功能是为了能够在启动整个进程树后杀死它。

这可能是个坏主意。我对你们的评论很感兴趣。

其他回答

这个脚本也可以工作:

# / bin / sh 而真正的 做 输入父进程id [type quit for exit] 读ppid if [$ppid -eq "quit" -o $ppid -eq "quit"] 退出0 fi I in ' ps -ef| awk '$3 == '$ppid' {print $2}' ' 做 Echo杀死$i 杀死我美元 完成 完成

pkill -TERM -P 27888

这将杀死父进程ID为27888的所有进程。

或者更有力:

CPIDS=$(pgrep -P 27888); (sleep 33 && kill -KILL $CPIDS &); kill -TERM $CPIDS

它将kill安排在33秒后,并礼貌地要求进程终止。

请参阅终止所有子代的答案。

你没有说你想要杀死的树是否是一个单独的进程组。(如果树是从服务器启动或shell命令行派生出来的,通常会出现这种情况。)您可以使用GNU ps发现进程组,如下所示:

 ps x -o  "%p %r %y %x %c "

如果它是您想要终止的进程组,只需使用kill(1)命令,但不给它一个进程号,而是给它一个组号的负数。例如,要终止5112组中的所有进程,请使用kill -TERM——-5112。

下面的shell函数与许多其他答案类似,但它在Linux和BSD (OS X等)上都可以工作,没有像pgrep这样的外部依赖:

killtree() {
    local parent=$1 child
    for child in $(ps -o ppid= -o pid= | awk "\$1==$parent {print \$2}"); do
        killtree $child
    done
    kill $parent
}

只使用属于该组的进程名删除该组:

kill -- -$(ps -ae o pid,pgrp,cmd | grep "[e]xample.py" | awk '{print $2}' | tail -1)

这是对olibre的答案的修改,但你不需要知道PID,只需要知道组中成员的名字。

解释:

要获得组id,您可以使用如下所示的参数执行ps命令,为您的命令grep它,但是使用引号格式化example.py,并使用括号作为第一个字母(这将过滤掉grep命令本身),然后通过awk过滤它以获得第二个字段,即组id。尾部的-1可以去除重复的组id。您使用$()语法将所有这些放到一个变量中,瞧——您得到了组id。用$(mess)替换上面的-groupid。