CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 2 min read

Orphans

In plain words: The reverse case is a parent that ends before its child. The child is now an orphan: a process whose parent has ended. Every process must have a parent, so the kernel gives the orphan a new one, the first process (PID 1, Level 0, page 4), or on some systems a designated helper process. The first process contains code that calls wait in a loop, so it reaps its adopted children when they end. That is why orphans do not become permanent zombies.

A program shows it. The child prints its parent's PID, sleeps one second and prints it again. Meanwhile the parent exits at once:

#include <stdio.h>
#include <unistd.h>
int main(void) {
    if (fork() == 0) {
        printf("child: parent is %d\n", (int)getppid());
        fflush(stdout);
        sleep(1);
        printf("child: parent is now %d\n", (int)getppid());
        return 0;
    }
    printf("parent exits\n");
    return 0;
}
parent exits
child: parent is 427
child: parent is now 1

The child's parent changed from 427 to 1. The kernel did this when process 427 ended.

Orphans are not always a problem. In fact they are used on purpose: a long-running background program is usually an orphan on purpose, so that it no longer depends on the terminal or the shell that started it. The next section shows how.

Orphan process

An orphan process is a process whose parent has ended. The kernel reassigns it to the first process (or another designated reaper), which collects its exit status when it ends.

Example: if a shell exits while a background command it started is still running, that command becomes an orphan and its parent PID becomes 1.

Check yourself: 1. Who adopts an orphan? 2. What does the adopting process do when the orphan ends? 3. Is an orphan always a bug?