jhj
jhj

Reputation: 41

Killing forked process in ruby with child processes

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?

Upvotes: 4

Views: 2673

Answers (2)

Sam Woods
Sam Woods

Reputation: 1850

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)

Upvotes: 2

7stud
7stud

Reputation: 48599

Behind the scene both system and backtick operations use fork to fork the current process and then they execute the given operation using exec .

Since exec replaces the current process it does not return anything if the operation is a success. If the operation fails then `SystemCallError is raised.

http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html

Upvotes: 2

Related Questions