xv6, line by line
user/zombie.c

user/zombie.c

C · 14 lines · annotated 100% · user program / library · upstream

About this file

zombie deliberately creates a zombie process, so that you can see one. A zombie is a process that has exited but whose parent has not yet called wait. Its open files and current directory are already released, but its memory, page table and process-table slot (with state ZOMBIE) stay allocated until a parent collects it with wait (kwait → freeproc); the slot holds the exit status the parent may ask for.

The program forks. The child exits at once; the parent sleeps for 5 clock ticks (about half a second) and then exits without calling wait. During that half second the child is a zombie. When the parent exits, kexit calls reparent, which hands the zombie to init; init’s endless wait loop (user/init.c) then collects it and the slot is freed (kwait → freeproc). That is what the comment’s “must be reparented at exit” refers to.

How to see it. Type zombie and press Ctrl-P within half a second. Ctrl-P makes the console interrupt handler call procdump (kernel/console.c:152), which prints every process’s PID, state and name. You see something like:

1 sleep  init
2 sleep  sh
23 sleep  zombie
24 zombie zombie

Process 23 is the parent, sleeping in pause; process 24 is the exited child. (The PIDs depend on how many processes ran before.) Press Ctrl-P again after the prompt returns and both are gone. To get more time, change the 5 to a larger number of ticks.

Read before: user/kill.c. Read next: kernel/proc.c (kexit, kwait, reparent).

1// Create a zombie process that
2// must be reparented at exit.
8int
9main(void)
11 if (fork() > 0)
12 pause(5); // Let child exit before parent.
13 exit(0);