Module 1 · Lesson 32 of 103

Zombies, orphans and live monitoring

Explain how zombies form and are reaped, tell orphans from zombies, and watch processes and threads live with top, htop and ps -L.

  • Beginner to advanced
  • 7 min read
  • 11 min lab
What you will need

Ubuntu 24.04 (WSL2, VM or container); a Raspberry Pi for the embedded sections

Your place in the module
By the end you can 3 objectives
  • Inspect a process through /proc/<pid> and distinguish threads from processes with ps -L and the thread id.
  • Explain how a zombie forms and is reaped, and why SIGKILL cannot be caught or ignored.
  • Watch processes live with top and htop and switch to the per-thread view.
Video coming soonZombies, orphans and live monitoring
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Job control and niceness
  • The shell's job control (&, jobs, fg, bg, Ctrl+Z) pauses and resumes processes; nohup and disown protect them from SIGHUP at logout.
  • nice ranges from -20 (highest priority) to +19 (lowest); an ordinary user may only raise it.
  • Load average counts runnable plus uninterruptible tasks over 1, 5 and 15 minutes, not CPU percentage.
01

Zombies, orphans and the reaping rules

5 min read

You can now run and control several jobs at once. This lesson answers why zombies appear, who reaps them, and how to watch processes live.

When a process exits, the kernel must keep its exit status available so the parent can ask what happened. The memory and files are released, but a small entry, essentially the PID and the exit status, remains until the parent collects it. That uncollected entry is a zombie, shown by ps as the Z state with <defunct> beside the name.

The collection is called reaping, and the parent does it with the wait() family of system calls, which in a shell is implicit: the shell reaps the children it starts, so the zombies you create in a terminal normally vanish instantly. A zombie forms only when a parent forgets or refuses to reap.

1the child exits

The child calls exit(); the kernel releases its memory but keeps a record of the exit status.

2the child becomes a zombie

With the parent not yet calling wait(), the child shows as Z or defunct.

3the parent reaps it

The parent calls wait() or waitpid(), reads the status, and the kernel frees the record.

4the parent dies first

If the parent exits instead, the orphan is reparented to PID 1, which reaps it.

Walk the zombie lifecycle below:

A child that exits becomes a zombie until its parent reaps it with wait(); if the parent dies first, the orphan is reparented to PID 1, which reaps it when it exits.

  • states: [{"id": "running", "label": "Running"}, {"id": "zombie", "label": "Zombie (Z)"}, {"id": "reaped", "label": "Reaped"}, {"id": "orphan", "label": "Orphan (reparented)"}]
  • transitions: [{"from": "running", "to": "zombie", "event": "child calls exit()"}, {"from": "zombie", "to": "reaped", "event": "parent calls wait()"}, {"from": "running", "to": "orphan", "event": "parent exits first"}, {"from": "orphan", "to": "reaped", "event": "orphan exits, PID 1 reaps"}, {"from": "zombie", "to": "reaped", "event": "parent dies, PID 1 reaps"}]

A small C program makes the zombie visible. The child exits at once, while the parent sleeps without calling wait(), so the child lingers as a zombie for the sleep duration:

c
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    pid_t pid = fork();
    if (pid == 0) {
        _exit(0);              /* the child exits immediately */
    }
    sleep(30);                 /* the parent never calls wait() */
    wait(NULL);                /* only reached after 30 seconds */
    return 0;
}
Zombie lifecycle: child exits, shows Z, reaped by killing the parent
learner@embeddex:~/lab$ # compile the lesson's C program
learner@embeddex:~/lab$ gcc -o zombie zombie.c
learner@embeddex:~/lab$ # run it in the background; the child exits at once
learner@embeddex:~/lab$ ./zombie &
learner@embeddex:~/lab$ # the child lingers as Z defunct until the parent reaps it
learner@embeddex:~/lab$ ps -o pid,ppid,stat,cmd | grep -E 'PID|zombie'
    PID    PPID STAT CMD
    187     181 S    ./zombie
    189     181 S    grep -E PID|zombie
    190     187 Z    [zombie] <defunct>
learner@embeddex:~/lab$ # a zombie cannot be killed; kill the parent so PID 1 reaps it
learner@embeddex:~/lab$ kill $!
learner@embeddex:~/lab$ # the zombie is gone
learner@embeddex:~/lab$ ps -o pid,ppid,stat,cmd | grep zombie || echo 'no zombie process remains
'
    192     181 S    grep zombie
learner@embeddex:~/lab$

While it sleeps, ps -o pid,ppid,stat,cmd shows the child as Z with <defunct>. A zombie cannot be killed: it is already dead. The only ways to reap it are for the parent to call wait(), or for the parent itself to exit so PID 1 adopts and reaps the child. In the lab, killing the parent is the demonstration.

Going deeperSIGCHLD, SIG_IGN, and the subreaper

The parent is normally told about a child's exit by SIGCHLD, whose default action is to discard the signal. Two subtleties follow. If the parent leaves SIGCHLD at its default and never calls wait(), zombies accumulate, which is the classic leak in a long-running parent. But if the parent explicitly sets SIGCHLD to SIG_IGN, the kernel reaps terminating children automatically, so no zombie forms at all, at the cost of the parent never learning the exit status. A third option is the child subreaper: a process that calls prctl(PR_SET_CHILD_SUBREAPER) becomes, in effect, a local init, adopting the orphans of its own descendants instead of letting them fall all the way to PID 1. Containers and process supervisors use a subreaper so that reparented children stay inside the tree they manage.

The orphan is the mirror image of the zombie: a process whose parent has died, but which is still running. The kernel reparents an orphan to PID 1 (or a subreaper), which will reap it when it eventually exits. Confusing the two is natural because both involve an absent parent, but an orphan is alive and running, while a zombie is dead and waiting to be collected.

Diagram in production
A child exiting into the zombie state, reaped by wait(), or reparented to PID 1 when the parent dies.
02

top, htop, threads and common mistakes

5 min read

ps is a snapshot; top is a live view that refreshes every few seconds and sorts by CPU use by default. Run it and the header shows the same load average as uptime, then a table of processes. The keys you need: P sorts by CPU, M by memory, k prompts for a PID and signal to kill it, r renicies a process, 1 toggles per-CPU lines, and q quits.

bash
top            # live, CPU-sorted; press k to kill, q to quit

htop is the same idea with a more readable interface, colour, and easier navigation: F3 searches, F4 filters, F5 switches to a tree view, F6 chooses the sort column, and F9 kills. Ubuntu Server images include it, but the WSL and minimal images do not, so run sudo apt install htop if it is missing; on a minimal board top ships with the procps package while htop may not be present at all.

Underneath the process abstraction sits the thread. Linux implements a process as a group of threads that share one address space, and each thread has its own thread ID, or TID. The number a program sees from getpid() is the thread group ID, while gettid() returns the thread's own ID; for a single-threaded process the two are equal.

ps -L or ps -eLf shows one row per thread, with the LWP column holding the thread ID. In /proc/<pid>/status, the Tgid line is the process ID and the Pid line is the thread ID, which is how you confirm the distinction without ps.

bash
ps -eLf | head          # one row per thread; LWP is the thread ID
grep -E '^(Tgid|Pid|Threads)' /proc/$$/status
Threads: one row per thread in ps -L, Tgid vs Pid in /proc
learner@embeddex:~/lab$ # one row per thread; the LWP column is the thread ID
learner@embeddex:~/lab$ ps -eLf | head
UID          PID    PPID     LWP  C NLWP STIME TTY          TIME CMD
root           1       0       1  6    1 15:13 ?        00:00:00 /sbin/init
root          24       1      24  2    1 15:13 ?        00:00:00 /usr/lib/systemd/systemd-journa
root          45       1      45  3    1 15:13 ?        00:00:00 /usr/lib/systemd/systemd-udevd
root          73      45      73  0    1 15:13 ?        00:00:00 (udev-worker)
root          74      45      74  1    1 15:13 ?        00:00:00 (udev-worker)
root          75      45      75  0    1 15:13 ?        00:00:00 (udev-worker)
root          76      45      76  0    1 15:13 ?        00:00:00 (udev-worker)
root          77      45      77  0    1 15:13 ?        00:00:00 (udev-worker)
root          78      45      78  0    1 15:13 ?        00:00:00 (udev-worker)
learner@embeddex:~/lab$ # a single-threaded shell: Tgid equals Pid, one thread
learner@embeddex:~/lab$ grep -E '^(Tgid|Pid|Threads)' /proc/$$/status
Tgid:   174
Pid:    174
Threads:        1
learner@embeddex:~/lab$ # systemd is one process running many threads
learner@embeddex:~/lab$ grep -E '^(Tgid|Pid|Threads)' /proc/1/status
Tgid:   1
Pid:    1
Threads:        1
learner@embeddex:~/lab$

This matters on an embedded board with a small RAM budget: a process you assumed was one task may be many threads, and top only shows the aggregate unless you press H to toggle thread view. The /proc/<pid>/stat file is the machine-readable single-line form of the same data that status lays out as names; ps parses stat, which is why its columns and /proc always agree.

Going deeperReading /proc/<pid>/stat

/proc/<pid>/stat is one line, and the fields are positional, which is why tools parse it by index. The first fields are: the PID, the command name in parentheses, then the state letter as field 3 and the PPID as field 4. Later fields hold the user and system CPU times, the priority and nice value, the thread count, the start time, and the memory sizes. The name in parentheses can itself contain spaces, so any parser must find the last closing parenthesis and count from there, a classic source of bugs. Prefer the labelled /proc/<pid>/status when a human is reading, and reserve stat for programs.

The same mistakes recur in every cohort, and each has a symptom, a cause and a fix.

Symptom Cause Fix
kill pid does nothing the process catches or ignores SIGTERM try kill -9 pid, the uncatchable signal
kill -9 does nothing and ps shows D uninterruptible sleep; the process never receives it resolve the device or filesystem wait
kill -9 on a <defunct> process does nothing a zombie is already dead reap via the parent, or kill the parent
renice -n -10 is rejected lowering nice needs root raise nice as a user, or use sudo
jobs does not list a job you started earlier jobs shows only the current shell's jobs, not those of another terminal or a script find it with pgrep -a or ps instead
nice -n 19 made no visible difference nice only matters when tasks compete for a CPU; on an idle machine every task runs anyway judge it under load, with top showing several busy tasks
& and && were confused two different operators cmd & backgrounds; a && b runs b only if a succeeds
Diagram in production
A process as a thread group: one PID for the process, distinct thread IDs per thread, and where /proc reports each.
03

Try it

1 min read

Open this session's lab and work through it in a scratch directory. Start a background job with sleep 300 &, confirm it with jobs, suspend it with Ctrl+Z, resume it with bg, bring it forward with fg, then signal it by job number with kill %1. Write a small script that creates a temporary file with mktemp, traps INT and TERM, and removes the file on EXIT, then prove the cleanup runs by interrupting it. Finally compile the short C program from the zombie section, run it, watch the child become <defunct> in ps, and reap it by killing the parent. Run the same steps over SSH on your Raspberry Pi and note which ps flags the board's BusyBox build is missing.

Key takeaways

  • A zombie is an exited child whose parent has not called wait(); killing the parent lets PID 1 reap it.
  • top and htop watch live processes; ps -L and /proc/<pid>/status expose the thread view underneath.
  • An orphan is a running child whose parent died; a zombie is a dead child waiting to be collected, and no signal removes it.
Reflect
  1. Explain to a colleague, in two sentences: inspect a process through /proc/<pid> and distinguish threads from processes with ps -L and the thread id.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close