I have a script below using Thor to run like a rake task managing 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 start ruby script.rb start
, it generates two subprocesses (total three). My question is how to kill all processes when I execute ruby script.rb stop
. I have seen around web that, on start, I should store the pid parent process into a file and, when stop, I read it and kill. The problem is that killing the parent doesn't kill the children. So I could save all three pids in the file and kill one by one later.
I'm asking myself what is the right way to do this, and whether the way I'm working with processes inside the start
is correct.