Wizard
Wizard

Reputation: 22113

The parent process keep trace of it child's termination status

I am reading up on the wait and waitpid functions and came across the following text:

When a process terminates, either normally or abnormally, the kernel notifies the parent by sending a SIGCHLD signal to the parent.

Then the parent should handle the termination.

I am confused about why the parent has to know its child is terminated. Surely, if the child has already terminated, it is gone and will never consume any resources.

For what reason does the parent have to be aware of it?

Upvotes: 0

Views: 93

Answers (1)

paxdiablo
paxdiablo

Reputation: 882336

If a process is starting other processes, it normally want to keep track of their state.

When a child process terminates, it almost disappears entirely. It becomes a zombie process and just enough information is kept around for another process (usually the parent) to be able to tell why it terminated (basically, its return code).

Then, when the parent successfully does a wait on the child, the return code is returned and the last remnants of the child are cleaned up.

And a parent doesn't have to do this. There are ways to start a child process that will have its parent modified, you can see the difference between:

sleep 3601 &
( sleep 3602 & )

The latter starts a child shell and, from within that, starts the sleep, then the child shell exits, so that child gets a new parent:

1 /sbin/init splash
|
+-- 1121 /usr/sbin/lightdm
    |
    +-- 1846 /usr/sbin/lightdm --session-child 12 19
        |
        +-- 2078 /sbin/upstart --user
        |
        +--- 29899 sleep 3602
        |
        +--- 2929 /usr/lib/gnome-terminal/gnome-terminal-server
             |
             +--- 2935 bash (my bash shell)
                  |
                  +--- 29891 sleep 3601

You can see here that one of the sleep processes still has my shell as the parent but the other one has been pushed up the process tree to upstart.

Often, it gets adopted by init(a) which has code specifically for reaping the zombies (wait-ing on them then throwing away the return code).


(a) Modern UNIXes can override this with a call to prctl() with the PR_SET_CHILD_SUBREAPER argument. This marks a process as a sub-reaper.

Then, when a parent dies, the fist sub-reaper when walking up the process tree becomes the new parent of its immediate children (with init being the ultimate reaper).

You can actually see this in the above process tree where it's evident that upstart has done exactly this. That means it was the first sub-reaper found when walking up the tree so the sleep that belonged to the process that died didn't go all the way up to init.

Upvotes: 3

Related Questions