2012-04-02 47 views
3

我正在寻找一种可靠的方法来实现一个分叉过程的回调,一旦它完成。在红宝石使用陷阱的叉回调

我尝试使用陷阱(请参阅下面的代码),但它似乎不时失败。

trap("CLD") { 
    pid = Process.wait 
    # do stuff 
} 

pid = fork { 
    # do stuff 
} 

虽然我没发现(通过谷歌)可能的解释为什么这可能会发生,我有一个很难搞清楚一个可能的解决方案。

回答

2

到目前为止我看到的唯一解决方案是在进程之间打开一个管道(父 - 读端,子 - 写端)。然后将父进程线程阻塞读取并捕获“断开的管道”或“管道关闭”的异常。

任何这些例外显然意味着子进程已经死亡。

更新:如果我没有错正常关闭管道将导致阻塞读取的EOF结果,并断开管道(如果子进程崩溃)将导致Errno::EPIPE异常。

#Openning a pipe 
p_read, p_write = IO.pipe 
pid = fork { 
    #We are only "using" write end here, thus closing read end in child process 
    #and let the write end hang open in the process 
    p_read.close 

} 
#We are only reading in parent, thus closing write end here 
p_write.close 

Thread.new { 
    begin 
    p_write.read 
    #Should never get here 
    rescue EOFError 
    #Child normally closed its write end 
    #do stuff 
    rescue Errno::EPIPE 
    #Chiled didn't normally close its write end 
    #do stuff (maybe the same stuff as in EOFError handling) 
    end 
    #Should never get here 
} 
#Do stuff in parents main thread 
+0

谢谢你的回答。我必须尝试一点。 – vise 2012-04-02 17:34:45

+0

这个解决方案的问题是父母只是等待叉子完成。我使用分叉的主要原因是父母继续已经在做的事情。 – vise 2012-04-03 15:26:55

+0

如果您在线程中进行侦听,它不会等待。查看我添加的代码片段。 – forker 2012-04-04 11:35:03