Question

How do you spawn a child process in Ruby?

I want to offload a block of code in my main process to child process to make it run concurrently. I also want to have the PID of the spawned child process so I can monitor and kill it if necessary.

 45  46191  45
1 Jan 1970

Solution

 54

In addition to Chris' great answer, remember to call Process.wait from your master in order to reap your child process, else you'll leave zombies behind.

Example as requested in comments:

pid = Process.fork do
  puts "child, pid #{Process.pid} sleeping..."
  sleep 5
  puts "child exiting"
end

puts "parent, pid #{Process.pid}, waiting on child pid #{pid}"
Process.wait
puts "parent exiting"
2008-11-20

Solution

 26

You can use the fork kernel method. Here is an example:

#!/usr/bin/env ruby
puts "This is the master process."

child_pid = fork do
  puts "This is the child process"
  exit
end

puts "The PID of the child process is #{child_pid}"

The fork method returns the PID of the process it forks and executes any code in the block passed. Like regular Ruby blocks it keeps the bindings of the parent process.

It is a good idea to make your forked process exit.

2008-11-20