7

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?

Ben
  • 1,272
  • 15
  • 30

2 Answers2

5

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.

Ben
  • 1,272
  • 15
  • 30
  • I wonder if the loop to get procs is reliable. On linux processes might be out of order so a few iterations might be needed to catch all. – akostadinov Nov 10 '15 at 22:10
-2

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
fakeleft
  • 2,732
  • 1
  • 27
  • 32
  • I don't see how this would work. `spawn` returns a single pid (not all child pids). The fact that you added that pid to an array and looped is superfluous. – AlexChaffee Nov 13 '15 at 12:45