问题描述
我有一个脚本 (script.sh),它产生了很多子进程.如果我通过./script.sh从外壳运行脚本,则可以通过
I have a script (script.sh) that spawns a whole lot of child processes. If I run the script from the shell via ./script.sh, I can kill the whole process tree via
kill -- -<PID>
其中PID是script.sh进程的进程ID(显然等于组ID).
where PID is the process ID of the script.sh process (this apparently equals the group ID).
但是,如果我通过
pid = Process.spawn(script.sh)
我无法杀死进程树.
Process.kill(9,pid)
仅杀死父进程.甚至更糟的是,以下
only kills the parent process. And even worst, the following
Process.kill(9,-Process.getpgid(pid)) ### Don't try this line at home
终止我的计算机.尝试通过
terminates my computer.Trying to kill the processes via
system("kill -- -#{pid}")
也失败.我应该如何从Ruby中杀死该进程树?
also fails.How am I supposed to kill this process tree from Ruby?
推荐答案
我想我已经找到了解决方案.将进程生成为
I think I have found the solution. Spawning the process as
pid = Process.spawn(script.sh, :pgroup => true)
使我能够通过
Process.kill(9,-Process.getpgid(pid))
默认情况下,bash group看起来好像正在处理,而Spawn默认情况下未启用.
It looks like bash groups processes by default, while Spawn doesn't enable this by default.
这篇关于从Ruby杀死进程组会杀死我的整个计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!