Killing forked process in ruby with child processes

Viewed 1980

The following code forks the main processes and runs a command in backticks. The kill at the end of the script only kills the forked process but not it's child processes (i.e. the sleep command).

pid = fork do
  Thread.new do
    `sleep 20`
  end
end
sleep(1)
Process.kill("HUP",pid)

Is there a way to kill all child processes (generated by backtick commands in threads in the forked process) other than searching through the process tree?

2 Answers

You can use

pid = Process.spawn('sleep 20')

to get the PID of the process immediately. Your code above would change to:

pid = Process.spawn('sleep 20')
sleep(1)
Process.kill('HUP',pid)
Related