首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby和Forking

Ruby和Forking
EN

Stack Overflow用户
提问于 2010-12-25 06:40:27
回答 1查看 790关注 0票数 1

关于Ruby forking的快速问题-我之前在Resque中遇到了一些forking代码,非常性感,但却让我被绊倒了几次。

我希望有人能给我更多关于这里发生的事情的细节。具体地说--似乎派生了一个子代(预期的),并将其直接踢入我的条件的“else”端(较少预期的。这是预期的行为吗?Ruby成语?

我的IRB技巧如下:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-25 06:47:06

这就是fork的工作原理。从文档中:

否则,fork调用返回两次,一次在父级,返回子进程的进程ID,一次在子级,返回nil。

因此,在父进程中'foo = fork‘是子进程的PID,在子进程中'foo = fork’是零,因此它在子进程中使用'else‘分支。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4528590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档