在Windows上的Ruby中杀死进程和子进程 [英] Kill process and sub-processes in Ruby on Windows
问题描述
当前,我正在一个命令提示符下执行此操作
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)
,然后在另一个
require 'win32/process'
Process.kill(1,<p>)
问题是我产生的进程(在本例中为Rails服务器)产生了一系列子进程. kill命令不会杀死它们,只会使它们成为没有父母的孤儿.
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.
有什么想法可以杀死整个及其所有子进程?
Any ideas how can I kill the whole spawned process and all its children?
推荐答案
我最终以以下方式解决了这个问题
I eventually solved this in the following manner
首先我安装了sys-proctable gem
First I installed the sys-proctable gem
gem install 'sys-proctable'
然后将原始发布的代码用于spawn
进程,然后使用以下代码将其杀死(为简便起见,省略了错误处理)
then used the originally posted code to spawn
the process, and the following to kill it (error handling omitted for brevity)
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
您当然可以将kill 9
更改为稍微有点进攻的东西,但这是解决方案的要旨.
You could change the kill 9
to something a little less offensive of course, but this is the gist of the solution.
这篇关于在Windows上的Ruby中杀死进程和子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!