Search code examples
cunixprocessforkwait

Waiting for grandchild after child process has died


I use the following code to wait for all child processes to finish:

int pid;
do {
    pid = wait(NULL);
} while (pid != -1);

However, it seems not to work in the event that I have grandchildren running when their parent processes have died. So for example, say I have process Alpha that forks a child Beta, and Beta forks a child Gamma. Then Beta dies while Gamma continues to run. I want to be able to make Alpha wait for Gamma to finish. The catch is that I am not able to store Gamma's process id - Alpha needs to be able to wait for all children, grandchildren, great-grandchildren, etc. to finish without knowing their individual pids. Can this be done (if so how)?


Solution

  • That cannot be done easily.

    When a process exits, its child processes are reparented to process 1 (init), because that is the only process that can be expected to wait() on any child process, even ones it does not know -- other processes might not know how to handle SIGCHLD, or even ignore processes they did not start, thus creating zombie processes.

    There is no way to declare that your process wants to clean up any grandchildren, while cleaning up children is always expected of you.

    The way to go would be to either have Beta go into a "waiting for children" state instead of terminating, or to start all child processes from Alpha.