简体   繁体   English

使用陷阱在ruby中的叉回调

[英]Fork callback in ruby using trap

I'm looking for a reliable way of implementing a callback on a forked process, once it has finished. 我正在寻找一种在分叉进程上完成回调的可靠方法。

I tried using trap (see the code below), but it appears to fail from time to time. 我尝试使用陷阱(参见下面的代码),但它似乎不时失败。

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

pid = fork {
  # do stuff
}

While I did found (via google) possible explanations why this may be happening, I'm having a hard time figuring out a possible solution. 虽然我确实发现(通过谷歌)可能的解释为什么会发生这种情况,但我很难找到可能的解决方案。

The only solution I see so far is to open a pipe between processes (parent - read end, child - write end). 到目前为止,我看到的唯一解决方案是在进程之间打开一个管道(parent - read end,child - write end)。 Then put the parent processes thread on blocking read and trap "broken pipe" or "pipe closed" exceptions. 然后将父进程线程放在阻塞读取和陷阱“断开管道”或“管道关闭”异常上。

Any of these exceptions will obviously mean that child process is dead. 任何这些例外显然意味着儿童过程已经死亡。

UPDATE: If I'm not wrong normally closed pipe will result into EOF result of blocking read, and broken pipe (if child process crashed) will result into Errno::EPIPE exception. 更新:如果我没错,通常关闭管道将导致阻塞读取的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM