Reputation: 2538
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
Upvotes: 1
Views: 808
Reputation: 3975
This is how fork works. From the documentation:
Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil.
So, in your parent 'foo = fork' is the PID of the child, and in the child 'foo = fork' is nil, thus it takes the 'else' branch in the child.
Upvotes: 4