Kill a process and subprocesses in Ruby on Windows

I am currently doing this on a single command line

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'm starting (the Rails server in this case) spawns a chain of subprocesses. The kill command does not kill them, but simply leaves them orphans without a parent.

Any ideas how I can kill the entire generated process and all its children?

+7
source share
2 answers

I eventually solved it as follows

I installed sys-proctable gem first

 gem install 'sys-proctable' 

then used the originally published code for the spawn 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 

You could change kill 9 to something a little less offensive, of course, but that's the essence of the solution.

+4
source

One-script solution without any gems. Run the script, CTRL-C to stop everything:

 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 
-2
source

All Articles