Search code examples
c++cmultiprocessingipcdaemon

Forking children in C and re-forking when they die


I have some code that forks a number of child "workers". Child labor :(

This works pretty good til a child dies due to some unpredictable error and the system throughput decreases.

What's a good pattern for monitoring for the children crashing, then re-forking them with the same params I fired them up with? I haven't written this type of code before and it looks like a little tricky.


Solution

  • Assuming Unix-like system, you can use wait or waitpid in the parent to monitor subprocesses synchronously. Alternatively, you can use SIGCHLD to monitor them asynchronously, and call wait or waitpid in the signal handler. You will get notified whenever a subprocesses terminates(including crashing).

    To re-fork a child with the same parameters when it crashes, you would have to record the parameters for each child.