Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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.

Any ideas how can I kill the whole spawned process and all its children?

like image 581
Ben Avatar asked Nov 21 '11 13:11

Ben


Video Answer


1 Answers

I eventually solved this in the following manner

First I installed the 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)

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 offensive of course, but this is the gist of the solution.

like image 195
Ben Avatar answered Oct 20 '22 01:10

Ben