我想杀死整个进程树。使用通用脚本语言实现这一目标的最佳方法是什么?我在寻找一个简单的解决办法。
当前回答
只使用属于该组的进程名删除该组:
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。
其他回答
谢谢你们的智慧。我的脚本在退出时留下了一些子进程,而否定提示使事情变得更容易。我写这个函数是为了在其他脚本中使用:
# kill my group's subprocesses: killGroup
# kill also myself: killGroup -x
# kill another group's subprocesses: killGroup N
# kill that group all: killGroup -x N
# N: PID of the main process (= process group ID).
function killGroup () {
local prid mainpid
case $1 in
-x) [ -n "$2" ] && kill -9 -$2 || kill -9 -$$ ;;
"") mainpid=$$ ;;
*) mainpid=$1 ;;
esac
prid=$(ps ax -o pid,pgid | grep $mainpid)
prid=${prid//$mainpid/}
kill -9 $prid 2>/dev/null
return
}
欢呼。
为了补充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中使用这个功能是为了能够在启动整个进程树后杀死它。
这可能是个坏主意。我对你们的评论很感兴趣。
下面是@zhigang的答案的一个变种,它没有AWK,只依赖于Bash的本地解析可能性:
function killtree {
kill -STOP "$1"
ps -e -o pid= -o ppid= | while read -r pid ppid
do
[[ $ppid = $1 ]] || continue
killtree "$pid" || true # Skip over failures
done
kill -CONT "$1"
kill -TERM "$1"
}
它在mac和Linux上都运行得很好。在您不能依赖于管理流程组的情况下——比如在编写测试必须在多个环境中构建的软件的脚本时——这种遍历树技术绝对是有用的。
pkill -TERM -P 27888
这将杀死父进程ID为27888的所有进程。
或者更有力:
CPIDS=$(pgrep -P 27888); (sleep 33 && kill -KILL $CPIDS &); kill -TERM $CPIDS
它将kill安排在33秒后,并礼貌地要求进程终止。
请参阅终止所有子代的答案。
如果你的系统上有pstrree和perl,你可以尝试这样做:
perl -e 'kill 9, (`pstree -p PID` =~ m/\((\d+)\)/sg)'
推荐文章
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- Linux Bash中双&和分号有什么区别?
- 如何合并2 JSON对象从2个文件使用jq?
- 在SSH会话中查找客户端的IP地址
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Linux删除大小为0的文件
- Spring引导应用程序作为服务
- 如何重定向标准derr和标准输出到不同的文件在同一行脚本?
- Windows和Linux上的c++编译:ifdef开关
- Linux: kill后台任务
- 如何修改Linux系统中打开文件的数量限制?
- 删除Bash脚本中的重复条目
- 如何将Bash命令的输出分配给变量?
- errno线程安全吗?