Managing Multiple Child Processes: Understanding Process Orchestration Through an Eight-Child Family

    This article uses the analogy of a parent raising eight children to explain core practices for managing multiple processes. It covers why to use multiprocessing, how to create and allocate child processes with `fork`, and how a parent process can monitor child status with `waitpid`, `SIGCHLD`, and health checks. A C example demonstrates a fixed-size worker pool with basic child reaping and restart considerations.

    Managing Multiple Child Processes: Understanding Process Orchestration Through an Eight-Child Family

    The television series A Family with Eight Children tells the story of a father raising eight children on his own and gradually creating order out of chaos. The situation is similar to multiprocess programming: a parent process creates multiple child processes, allocates resources, tracks the state of each child, and responds quickly when something goes wrong.

    Using this analogy, this article reviews the core practices of managing multiple child processes.

    1. Why Use Multiple Processes?

    At the operating-system level, multiprocessing is a common way to use multiple CPU cores and isolate failures. Its main benefits include:

    • Strong isolation: Each child process has its own address space. A crash in one child process does not directly corrupt the parent process or its sibling processes.
    • High parallelism: Child processes can be scheduled on different CPU cores and execute concurrently, making multiprocessing suitable for CPU-intensive workloads.
    • A mature ecosystem: Toolchains, debuggers, and monitoring solutions are widely available.

    The trade-off is higher resource consumption. Inter-process communication is also more complex than sharing memory between threads. Whether multiprocessing is appropriate depends on the characteristics of the workload.

    2. Creating Child Processes: fork and Resource Allocation

    On Unix-like systems, child processes are commonly created with fork. After fork returns, the parent and child processes continue executing the same code and use the return value to determine their identities.

    The following example shows a fixed-size worker pool. It can be compiled and run directly after replacing the worker path with the actual executable path.

    1. #include <errno.h>
    2. #include <signal.h>
    3. #include <stdio.h>
    4. #include <stdlib.h>
    5. #include <string.h>
    6. #include <sys/types.h>
    7. #include <sys/wait.h>
    8. #include <unistd.h>
    9. extern char **environ;
    10. #define MAX_WORKERS 8
    11. typedef struct {
    12. pid_t pid; /* 0 means that this slot is idle */
    13. int restarts; /* Total restart count, used by backoff strategies */
    14. } worker_t;
    15. static worker_t workers[MAX_WORKERS];
    16. static volatile sig_atomic_t sigchld_flag = 0;
    17. static void on_sigchld(int sig) {
    18. (void)sig;
    19. sigchld_flag = 1; /* Only set a flag in the handler; keep other logic in the main loop */
    20. }
    21. static pid_t spawn_worker(int slot) {
    22. pid_t pid = fork();
    23. if (pid < 0) {
    24. perror("fork"); /* Handle fork failures, such as resource exhaustion, explicitly */
    25. return -1;
    26. }
    27. if (pid == 0) {
    28. /* Close unrelated file descriptors inherited from the parent here if necessary */
    29. char *argv[] = {"worker", NULL};
    30. execve("/usr/local/bin/worker", argv, environ);
    31. _exit(127); /* Exit immediately if execve fails */
    32. }
    33. workers[slot].pid = pid; /* Track the slot by array index, not by using the PID as an index */
    34. return pid;
    35. }
    36. static void reap_children(void) {
    37. int status;
    38. pid_t pid;
    39. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
    40. for (int i = 0; i < MAX_WORKERS; i++) {
    41. if (workers[i].pid == pid) {
    42. workers[i].pid = 0;
    43. if (WIFEXITED(status))
    44. printf("Worker %d exited with code %d\n",
    45. (int)pid, WEXITSTATUS(status));
    46. else if (WIFSIGNALED(status))
    47. printf("Worker %d was terminated by signal %d\n",
    48. (int)pid, WTERMSIG(status));
    49. break;
    50. }
    51. }
    52. }
    53. }
    54. int main(void) {
    55. struct sigaction sa;
    56. memset(&sa, 0, sizeof(sa));
    57. sa.sa_handler = on_sigchld;
    58. sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
    59. sigemptyset(&sa.sa_mask);
    60. if (sigaction(SIGCHLD, &sa, NULL) < 0) {
    61. perror("sigaction");
    62. return 1;
    63. }
    64. for (int i = 0; i < MAX_WORKERS; i++)
    65. spawn_worker(i);
    66. while (1) {
    67. if (sigchld_flag) {
    68. sigchld_flag = 0;
    69. reap_children();
    70. /* Use exit records here to decide whether to restart a slot with backoff */
    71. }
    72. sleep(1); /* Periodic polling provides a fallback */
    73. }
    74. }

    In practice, there are two common creation strategies:

    1. Create all workers at startup: Fork all child processes during initialization. This works well for worker pools with a fixed size.
    2. Create workers on demand: Add child processes as the workload increases. This is suitable for workloads with significant fluctuations. A concurrency limit is required; otherwise, system resources may be exhausted.

    Regardless of the strategy, set a process-count limit and adjust it according to system load indicators. This is the basic idea behind a process pool.

    3. Monitoring State: How the Parent Tracks Its Children

    The parent process needs to learn about child-process state changes promptly. Three common approaches are listed below:

    Method Trigger Advantage Limitation
    waitpid polling The parent calls it actively Simple to implement and does not involve signals Polling introduces delay and may cause unnecessary CPU usage
    SIGCHLD signal The kernel notifies the parent when a child exits Event-driven with low latency Signal handlers are restricted and must be written carefully
    Health checks The parent probes periodically Can detect processes that are stuck