我想杀死整个进程树。使用通用脚本语言实现这一目标的最佳方法是什么?我在寻找一个简单的解决办法。
当前回答
如果你知道传递父进程的pid,下面这个shell脚本应该可以工作:
for child in $(ps -o pid,ppid -ax | \
awk "{ if ( \$2 == $pid ) { print \$1 }}")
do
echo "Killing child process $child because ppid = $pid"
kill $child
done
其他回答
pkill -TERM -P 27888
这将杀死父进程ID为27888的所有进程。
或者更有力:
CPIDS=$(pgrep -P 27888); (sleep 33 && kill -KILL $CPIDS &); kill -TERM $CPIDS
它将kill安排在33秒后,并礼貌地要求进程终止。
请参阅终止所有子代的答案。
如果你想按名称杀死一个进程:
killall -9 -g someprocessname
or
pgrep someprocessname | xargs pkill -9 -g
使用psutil使用python非常容易做到这一点。只要用pip安装psutil,你就有了一整套进程操作工具:
def killChildren(pid):
parent = psutil.Process(pid)
for child in parent.get_children(True):
if child.is_running():
child.terminate()
为了补充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 杀死我美元 完成 完成
推荐文章
- 理解PrimeFaces处理/更新和JSF f:ajax执行/呈现属性
- 我可以在/etc/hosts中映射主机名*和端口*吗?
- Tar归档,从文件列表中获取输入
- 寻找不属于特定用户的文件
- 如何使用gnu cp命令将一个文件复制到多个目录
- 守护进程的错误响应:已被集装箱使用"
- 使用gcc命令行从.c文件构建.so文件
- bash中的字符串比较。[[:没有找到
- 如何在Bash脚本中使用密码执行sftp命令?
- 在Bash中将命令行参数转换为数组
- 为什么用反斜杠开始shell命令?
- 如何找到Java堆大小和内存使用(Linux)?
- 遍历带空格的文件列表
- 在Bash中检查传递的参数是否为文件或目录
- Bash:无限睡眠(无限阻塞)