Skip to content
Visual explainer 3h to learn 4 steps

Exit, zombies, orphans & the environment

Avoid zombie processes and pass configuration through the environment.

By Invicly Tech, , in Linux System Programming. About 11 minutes to read.

Topic 16 of 42

In short

When a process exits, the kernel keeps a small record of its exit status until the parent collects it with wait; until then the child is a zombie. If the parent dies first, the child becomes an orphan and is adopted by PID 1 or a designated subreaper, which reaps it. Each process also inherits an environment of KEY=value strings from its parent.

Explained simply

When a process finishes, it does not vanish at once. The kernel frees its memory and closes its files, but it keeps a tiny note: "process 4211 ended with code 0". The parent may want to read that note, so the kernel holds it until the parent asks. A finished process waiting to be asked about is called a zombie.

Zombies are harmless in small numbers. They use no CPU and no memory, only a PID and a line in the process table. The trouble starts when a buggy parent never asks. Thousands of zombies can pile up until the system runs out of PIDs and nothing new can start.

The opposite case is an orphan: the parent dies while the child is still running. The child is not left alone. The kernel gives it a new parent, normally PID 1, which waits for it when it finishes so no zombie remains.

Every process also carries a small list of settings called the environment, such as HOME=/home/ana or LANG=en_US.UTF-8. A child gets a copy of its parent's list. It can change its own copy, but the parent never sees those changes, a bit like a photocopy you scribble on.

Press Play on a diagram to walk through it one step at a time.

MapA process tree with a zombie and an orphan
systemd (PID 1)
  • bash (PID 200)
    • sleep (PID 201): running
    • ls (PID 202): zombie until bash waits
  • worker (PID 305): orphan
    • Parent died, reparented to PID 1
    • PID 1 reaps it when it exits
SequenceAn orphan is adopted and reaped
Parent
Kernel
Child
PID 1
  1. 1exits while the child still runs
    Parent to Kernel: exits while the child still runs
  2. 2PPID changed to 1 (or a subreaper)
    Kernel to Child: PPID changed to 1 (or a subreaper)
  3. 3exit(0) later
    Child to Kernel: exit(0) later
  4. 4SIGCHLD
    Kernel to PID 1: SIGCHLD
  5. 5waitpid collects the status
    PID 1 to Kernel: waitpid collects the status

In depth

What really happens at exit

Returning from main is the same as calling exit with that value. exit first runs the functions registered with atexit, in reverse order of registration, then flushes and closes all stdio streams, and finally calls _exit. _exit (the exit_group system call in glibc) goes straight to the kernel.

The kernel then closes every descriptor, releases the memory, detaches from shared resources, sends SIGCHLD to the parent and hands any children to a new parent. The process becomes a zombie holding only its PID, its exit status and resource usage numbers (CPU time and so on). When the parent calls wait, those numbers are returned and the last trace disappears.

FlowFrom exit() to fully gone
  1. 1
    exit(status)

    atexit handlers run, stdio is flushed.

  2. 2
    _exit

    Enter the kernel; no more user code.

  3. 3
    Release resources

    Close fds, free memory, reparent children.

  4. 4
    Zombie (Z)

    Only PID and status remain; SIGCHLD sent.

  5. 5
    Parent waits

    Status returned, entry removed.

Three ways to never leave zombies

The direct way is to wait. A parent that starts one child at a time can just call waitpid. A server that starts many children should reap in a loop: while (waitpid(-1, &st, WNOHANG) > 0), run from its event loop or from a SIGCHLD handler. waitpid is async-signal-safe, so it is allowed in a handler; save and restore errno around it.

The second way is to say you never care: set SIGCHLD to SIG_IGN, or install a handler with the SA_NOCLDWAIT flag. Then children are reaped automatically by the kernel, but you also lose their exit statuses.

The third way is the double fork: the parent forks a child, the child forks a grandchild and exits at once, and the parent reaps the child. The grandchild is now an orphan adopted by PID 1, which reaps it later. Classic daemons use this.

  • ps -eo pid,ppid,stat,comm | awk '$3 ~ /^Z/' lists zombies and their parents
  • kill -9 on a zombie does nothing; it is already dead
  • Killing the parent makes PID 1 adopt and reap the zombies

Orphans, subreapers and containers

When a parent dies, the kernel looks upward for a new parent. If an ancestor marked itself with prctl(PR_SET_CHILD_SUBREAPER, 1) (Linux 3.4 and later), the orphan goes there. Otherwise it goes to PID 1 of its PID namespace. systemd --user and container runtimes use subreapers so they keep track of everything their services start.

This matters a lot in containers. Your app may be PID 1 inside the container, so every orphan is handed to it. If the app never calls wait, zombies collect. PID 1 is also special for signals: it ignores any signal for which it has no handler, so a plain SIGTERM may do nothing. That is why people run a tiny init such as tini, or use docker run --init, in front of the real program.

The environment: environ, getenv and setenv

The environment is an array of KEY=value strings that ends with NULL. It reaches main through the global variable environ and is copied into the new program by execve. getenv reads a value, setenv adds or replaces one, and unsetenv removes one. Avoid putenv: it stores your pointer itself, so changing or freeing that buffer later changes the environment.

Arguments and environment together must fit the kernel's limit, shown by getconf ARG_MAX (usually 2 MiB, a quarter of the default 8 MiB stack limit). /proc/PID/environ shows the environment the program started with; later setenv calls are usually not reflected there. setenv is not thread-safe, so set what you need at startup, before creating threads.

  • env -i prog runs prog with an empty environment
  • VAR=value prog sets one variable just for prog
  • tr '\0' '\n' < /proc/PID/environ shows the starting environment

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Compare exit and _exit~45m
  2. 2
    Create and reap a zombie~45m
  3. 3
    Explain orphan adoption by init~45m
  4. 4
    Read and set environment variables~45m

Key points

  • Zombies use no CPU or memory, only a process table entry and a PID.
  • Fix zombies by having the parent wait, for example from a SIGCHLD handler.
  • exit runs atexit handlers and flushes stdio; _exit returns to the kernel immediately.
  • The environment is copied at fork and exec; a child's changes never flow back to the parent.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
  if (fork() == 0) _exit(0);      // child exits immediately
  printf("child is a zombie for 30s: ps -o pid,stat,comm\n");
  sleep(30);                      // parent never calls wait
  setenv("APP_MODE", "debug", 1);
  printf("APP_MODE=%s\n", getenv("APP_MODE"));
  return 0;
}

Run it and look for a Z state in ps from another terminal.

Hunting zombies on a production server

An alert says the process count keeps climbing. Step 1: count processes in state Z. Step 2: group them by parent PID; usually one parent owns them all. Step 3: look at that parent, which is a program that forgets to call wait. Step 4: the real fix is in its code (reap in a SIGCHLD handler or loop). As a short-term fix, restarting the parent makes PID 1 adopt and reap every zombie at once.

bash
ps -eo stat | grep -c '^Z'                 # how many zombies
ps -eo ppid,stat | awk '$2 ~ /^Z/ {print $1}' | sort | uniq -c | sort -rn
ps -o pid,user,etime,cmd -p 2345           # inspect the guilty parent
cat /proc/sys/kernel/pid_max               # the ceiling we are heading to
sudo systemctl restart myworker            # temporary relief only

Giving a child a clean, controlled environment

Sometimes you want a child to see only the variables you choose, for example to avoid leaking secrets such as AWS keys from the parent. execle takes the environment as its last argument. Here the child shell sees APP_MODE and PATH, but not HOME, so it prints home=unset. The parent's own environment is untouched.

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

int main(void) {
  char *env[] = { "APP_MODE=prod", "PATH=/usr/bin:/bin", NULL };
  pid_t pid = fork();
  if (pid < 0) { perror("fork"); return 1; }
  if (pid == 0) {
    execle("/bin/sh", "sh", "-c", "echo mode=$APP_MODE home=${HOME:-unset}", (char *)NULL, env);
    perror("execle"); _exit(127);
  }
  waitpid(pid, NULL, 0);
  return 0;
}

Quick reference

  • A zombie holds only a PID, exit status and usage numbers until its parent waits
  • Reap many children: while (waitpid(-1, &st, WNOHANG) > 0) { ... }
  • signal(SIGCHLD, SIG_IGN) makes the kernel reap children automatically
  • Orphans go to the nearest subreaper, else PID 1 of their PID namespace
  • exit runs atexit handlers and flushes stdio; _exit skips both
  • Use setenv and unsetenv; avoid putenv, which keeps your pointer
  • docker run --init adds a tiny PID 1 that reaps zombies and forwards signals

Common mistakes

  • Trying to kill -9 a zombie; it is already dead and only its parent can reap it.
  • Never reaping children in a long-running server until the PID limit is reached.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which resource does a zombie process still hold?

Question 2

2You set SIGCHLD to SIG_IGN in a parent. What changes?

Question 3

3Your app runs as PID 1 in a container and docker stop takes 10 seconds then kills it. Why?

Question 4

4A child process runs setenv("MODE", "x", 1). What does the parent see for MODE afterwards?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a zombie on purpose in the shell and watch it in ps.

  2. Exercise 2medium

    Register two atexit handlers and show the order they run in. Then show that calling _exit skips them.

  3. Exercise 3hard

    Write a parent that starts 10 short-lived children and reaps all of them from a SIGCHLD handler, never leaving a zombie and never losing an exit even when signals merge.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How do I kill a zombie process?
You cannot; it is already dead. Make its parent call wait, or stop the parent so PID 1 adopts the zombie and reaps it.
Are zombies a security risk?
Not directly, but enough of them can use up the PID space or a user's process limit, which stops new programs from starting.
What does defunct mean in ps output?
It is the same as state Z: the process has exited and is waiting for its parent to collect the status.
Why does my child process not see a variable I exported later?
The child got a copy of the environment when it was created. Variables set afterwards in the parent only reach children started later.

Go deeper

ShareXLinkedInWhatsApp