Ruby和分叉

时间:2010-12-24 22:40:27

标签: ruby

关于Ruby forking的快速问题 - 我之前在Resque中遇到了一些分叉的代码,这些代码很性感,但却让我吵了几下。

我希望有人能够详细介绍一下这里发生了什么。具体来说 - 看起来分叉会产生一个孩子(预期)并将其直接踢到我的病情的“其他”方面(预期较少。这是预期的行为吗?一个Ruby成语?

我的IRB黑客在这里:

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

1 个答案:

答案 0 :(得分:4)

这就是fork的工作原理。来自文档:

  

否则,fork调用返回   两次,一次在父母身边,返回   孩子的进程ID,一次   在孩子身上,归零。

所以,在你的父亲'foo = fork'中是孩子的PID,而在孩子'foo = fork'中是nil,因此它会在孩子中使用'else'分支。

相关问题