2

In Ruby, how do I ensure that child processes spawned from my program don't keep running when my main process exits or is killed?

Initially I thought I could just use at_exit in the main process, but that won't work if my main process gets kill -9ed or calls Kernel.exec. I need a solution that is (basically) foolproof, and cross-platform.

Ajedi32
  • 45,670
  • 22
  • 127
  • 172
  • How are you starting the child process in question? For instance, is it an `Open4.open4` block? – Neil Slater Aug 13 '13 at 20:30
  • 2
    Note if your main process is `kill -9`ed then there is very little you can do in code. The person running the `kill 9` has made the decision that it is their problem to tidy up. – Neil Slater Aug 13 '13 at 20:33
  • @NeilSlater I'm using a library ([childprocess](https://github.com/jarib/childprocess)) which uses different methods for starting the child process depending on the platform. – Ajedi32 Aug 13 '13 at 20:39

1 Answers1

0

If you have to handle kill -9 termination for your parent app, then you have only a couple of choices that I can see:

  • Create a work queue manager and spawn/kill child processes from work queue manager. If you can't guarantee that the work queue manager won't also be killed without warning, then option 2 is your only choice I think, since the only thing you know for sure is that the child processes are still running.
  • Have the child processes check a "heartbeat" from the parent process through RPC or monitoring parent PID in memory or watching a date/time on keep-alive file in /tmp to make sure it's current.
    • If the child processes fail to see the parent processes doing it's job of either responding to RPC messages, staying in memory itself, or keeping a file date/time current the child processes must kill themselves.
Steve Midgley
  • 2,226
  • 2
  • 18
  • 20
  • Thanks for the answer. I basically ended up going with option 2, except that instead of the child process directly checking the heartbeat of the parent I spawned a separate process to handle that. – Ajedi32 Sep 27 '13 at 15:46