Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
vise Avatar asked Jul 17 '26 01:07

vise


1 Answers

The only solution I see so far is to open a pipe between processes (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.

#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
like image 193
forker Avatar answered Jul 20 '26 16:07

forker