Part 2 of 6 · 3 min read
Zombies
In plain words: When a process ends, the kernel frees its memory and open files at once. But it keeps a small record, containing the process's ID and exit status, until the parent asks for it with wait. The parent may want to know whether the child succeeded. A shop keeps a customer's receipt until the customer takes it. The analogy stops at the end: the record is tiny, but the number of records the system can hold is limited.
A process that has ended and whose record has not been collected is a zombie. It is dead, runs no code and uses no memory, yet it still has a PID and a slot in the process table. It shows as state Z in ps (page 2).
A program shows it. The child ends at once. The parent waits one second, shows the child with ps, then calls waitpid and shows it again:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) _exit(0);
printf("child %d has ended, parent has not called wait yet\n", (int)pid);
char cmd[64];
snprintf(cmd, sizeof cmd, "ps -o pid,ppid,stat,comm -p %d", (int)pid);
fflush(stdout);
sleep(1);
if (system(cmd) < 0) return 1;
waitpid(pid, NULL, 0);
printf("after wait:\n");
fflush(stdout);
if (system(cmd) < 0) return 1;
return 0;
}
Output on the test machine:
child 414 has ended, parent has not called wait yet
PID PPID STAT COMMAND
414 413 Z z1
after wait:
PID PPID STAT COMMAND
Before the wait, the child is listed with state Z. After the wait, the line is gone. The act of collecting a zombie is called reaping it.
One zombie is harmless. A server that forks a child for each request and never waits slowly fills the table of PIDs. The test machine allows up to 32,768 PIDs (the value in /proc/sys/kernel/pid_max), and when they are all used, fork fails with an error. Zombies cannot be removed with kill, because they are already dead. They go away when the parent calls wait, or when the parent itself ends, because then the first process adopts and reaps them (next section).
Zombie process
A zombie process is a process that has ended but still has an entry in the process table, holding its exit status, because its parent has not yet collected it with wait or waitpid. It uses no memory or processor time but occupies a PID.
Example: a server that forks a child for each client and never calls wait leaves a zombie behind every time a child finishes.
Check yourself:
1. Which ps state letter marks a zombie?
2. Why does kill -9 not remove a zombie?
3. What resource does a large number of zombies exhaust?