2012-04-02 7 views
3

フォークされたプロセスでコールバックを実装する信頼できる方法を探しています。トラップを使ったRubyでのフォークコールバック

私はトラップ(下記のコードを参照)を使用しようとしましたが、時々失敗するようです。 (グーグル経由)

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

pid = fork { 
    # do stuff 
} 

Iが見つからなかったが可能な説明、なぜこれが起こっても、私は可能な解決策を考え出す苦労しています。

答えて

2

私が今までに見た唯一の解決策は、プロセス間でパイプを開くことです(親リードエンド、子ライトエンド)。次に、親プロセススレッドをブロッキング読み取りとトラップ "broken pipe"または "pipe closed"例外に置きます。

これらの例外は、明らかに子プロセスが停止していることを意味します。

更新:私が間違っていないと、通常は閉じたパイプは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

+0

この解決策の問題は、親がフォークが終了するのを待つことです。私がフォークを使用している主な理由は、親が既に中断していないことを続けることです。 – vise

+0

スレッド内でリスニングを行うのであれば、ただ待っているだけではありません。私が追加したコードスニペットを見てください。 – forker

関連する問題