How to kill all the processes inside the ruby ​​Thor at the bus stop?

I have a script below, using Thor to run, like rake job management ARGV.

#!/usr/bin/env ruby
require "thor"

class Run < Thor

  desc "start", "start script"
  def start
      p1 = fork{ loop... }
      p2 = fork{ loop... }

      # 3 processes running

      Process.detach(p1)
      Process.waitpid(p1)

  end

  desc "stop", "stop script"      
  def stop
    # kill all 3 pids
  end

end

Run.start

When launched, ruby script.rb startit generates two subprocesses (total three). My question is how to kill all processes when I execute ruby script.rb stop. I saw on the Internet that, first, I have to save the parent pid process to a file, and when it stops, I read it and kill it. The problem is that killing a parent does not kill children. Therefore, I could save all three pids in a file and kill one by one later.

I ask myself how to do this correctly, and whether I work correctly with processes inside start.

+5
source share
1 answer

pid, :

# Find child pids, works on Linux / OSX
def child_pids(pid)
  pipe = IO.popen("ps -ef | grep #{pid}")
  pipe.readlines.map do |line|
    parts = line.strip.split(/\s+/)
    parts[1].to_i if parts[2] == pid.to_s and parts[1] != pipe.pid.to_s
  end.compact
end

# kill -9 every child
child_pids(parent_pid).each { |pid| Process.kill('TERM', pid) }
0

All Articles