Ruby and Forking
- by Cory
Quick question about Ruby forking - I ran across a bit of forking code in Resque earlier that was sexy as hell but tripped me up for a few.
I'm hoping for someone to give me a little more detail about what's going on here. Specifically - it would appear that forking spawns a child (expected) and kicks it straight into the 'else' side of my condition (less expected. Is that expected behavior? A Ruby idiom?
My IRB hack here:
def fork
return true if @cant_fork
begin
if Kernel.respond_to?(:fork)
Kernel.fork
else
raise NotImplementedError
end
rescue NotImplementedError
@cant_fork = true
nil
end
end
def do_something
puts "Starting do_something"
if foo = fork
puts "we are forking from #{Process.pid}"
Process.wait
else
puts "no need to fork, let's get to work: #{Process.pid} under #{Process.ppid}"
puts "doing it"
end
end
do_something