Fork callback in ruby ​​using trap

I am looking for a reliable way to execute a callback on a forked process as soon as it finishes.

I tried using a trap (see code below) but it doesn't work from time to time.

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

pid = fork {
  # do stuff
}

      

While I have found (via google) possible explanations for why this might be happening, I am having a hard time finding a possible solution.

+3


source to share


1 answer


The only solution I see so far is to open a pipe between processes (parent is end of read, end of write is write). Then set the parent process thread to read lock and "broken pipe" or "closed pipes" traps.

Any of these exceptions obviously means that the child process is dead.



UPDATE: If I'm not mistaken, a normally closed pipe will result in an EOF read lock, and a broken pipe (if the child has crashed) will result in an exception 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

      

+2


source







All Articles