在 Windows 上的 Ruby 中杀死进程和子进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8212483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Kill process and sub-processes in Ruby on Windows
提问by Ben
Currently I'm doing this in one command prompt
目前我正在一个命令提示符下执行此操作
require 'win32/process'
p = Process.spawn("C:/ruby193/bin/bundle exec rails s")
puts p
Process.waitpid(p)
and then in another
然后在另一个
require 'win32/process'
Process.kill(1,<p>)
The problem is that the process I spawn (the Rails server in this case) spawns a chain of sub-processes. The kill command doesn't kill them, it just leaves them orphaned with no parent.
问题是我生成的进程(在本例中是 Rails 服务器)生成了一系列子进程。kill 命令不会杀死他们,只会让他们成为没有父母的孤儿。
Any ideas how can I kill the whole spawned process and all its children?
任何想法我怎样才能杀死整个产生的过程及其所有的孩子?
采纳答案by Ben
I eventually solved this in the following manner
我最终通过以下方式解决了这个问题
First I installed the sys-proctable gem
首先我安装了 sys-proctable gem
gem install 'sys-proctable'
then used the originally posted code to spawn
the process, and the following to kill it (error handling omitted for brevity)
然后将最初发布的代码用于spawn
该进程,并使用以下代码将其杀死(为简洁起见省略了错误处理)
require 'win32/process'
require 'sys/proctable'
include Win32
include Sys
to_kill = .. // PID of spawned process
ProcTable.ps do |proc|
to_kill << proc.pid if to_kill.include?(proc.ppid)
end
Process.kill(9, *to_kill)
to_kill.each do |pid|
Process.waitpid(pid) rescue nil
end
You could change the kill 9
to something a little less offensiveof course, but this is the gist of the solution.
当然,您可以将其更改kill 9
为不那么令人反感的东西,但这是解决方案的要点。
回答by fakeleft
One-script solution without any gems. Run the script, CTRL-C to stop everything:
没有任何 gem 的单一脚本解决方案。运行脚本,CTRL-C 停止一切:
processes = []
processes << Process.spawn("<your process>")
loop do
trap("INT") do
processes.each do |p|
Process.kill("KILL", p) rescue nil
Process.wait(p) rescue nil
end
exit 0
end
sleep(1)
end