Ruby and Forking

Posted by Cory on Stack Overflow See other posts from Stack Overflow or by Cory
Published on 2010-12-24T22:40:26Z Indexed on 2010/12/24 22:54 UTC
Read the original article Hit count: 356

Filed under:

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

© Stack Overflow or respective owner

Related posts about ruby