Diagnose zombie processes by checking parent reaping
A batch job has finished, yet more and more <defunct> entries remain in the process list. CPU usage is close to zero, and the task scheduler occasionally fails to create new processes. In this situation, the first thing to check is not available memory, but whether the parent process has collected its children's exit status. Adding memory to a dedicated server cannot fix missing reaping logic, and forcibly killing the listed PIDs will not solve the problem either.
This article uses Debian 12, Debian 13, or Ubuntu Server 24.04 LTS, together with procps and the Python 3 standard library, to build a diagnostic and reproduction workflow. The experiment creates only one child process; it does not attempt to exhaust process capacity on a production system.
1. Distinguish zombies from sleeping processes and uninterruptible waits
When a child process exits, the kernel retains its exit status and a small amount of accounting information so that the parent can retrieve them through interfaces such as wait and waitpid. Until that information is collected, the child is a zombie, with Z in its process state. It no longer executes code or retains its original user-space address space, but it still occupies a process table entry and a PID.
S usually indicates interruptible sleep, while D indicates an uninterruptible wait. A process is not necessarily a zombie just because it has shown no activity for a long time. <defunct> in the command name is a supporting clue; use the state field to identify zombies.
ps -eo pid=,ppid=,stat=,etimes=,comm= |
awk '$3 ~ /^Z/ {print}'
The output fields are, in order: PID, parent PID, state, elapsed seconds since the process started, and command name. etimes is not the time spent as a zombie, so it cannot establish how long a process has been in that state.
A zombie process has already exited. Sending it a force-kill signal does not reap it on the parent's behalf. What needs investigation is the parent's wait logic.
A briefly visible Z may simply mean that the sample caught the normal interval before reaping. To identify a problem, check whether the number of zombies under the same parent keeps increasing and whether they remain after the tasks have finished.
2. Preserve parent-child relationships and process identity
Save a full snapshot first, then narrow the investigation to the suspicious PPID. These commands only read information; they do not send signals:
umask 077
snapshot=$(mktemp /tmp/process-evidence.XXXXXX)
ps -eo pid,ppid,stat,lstart,etimes,comm --forest > "$snapshot"
printf '%s\n' "$snapshot"
Next, enter the suspicious parent PID into a variable and inspect the parent and its direct children:
read -r -p 'Parent PID: ' parent
if [[ "$parent" =~ ^[1-9][0-9]*$ ]]; then
ps -p "$parent" -o pid,ppid,stat,lstart,comm
ps --ppid "$parent" -o pid,ppid,stat,lstart,comm
fi
Record the start time as well, because PIDs are reused. A few minutes later, the same number may belong to a different process, so an old snapshot must not be used directly to decide which process to terminate. Processes can also exit between the two queries, meaning the two outputs are not an atomic snapshot.
If systemd manages the parent, use systemctl status with its PID to help identify the owning unit, then verify the startup command and logs. Do not terminate processes in bulk based only on their name; programs with the same name may serve different workloads.
By default, evidence files should contain only the necessary fields. Full command lines may include tokens or connection parameters. If collecting them is necessary, restrict access separately so that diagnostic evidence does not become a copy of your credentials.
3. Reproduce exit and reaping with one child process
The following script lets a child exit, waits until it observes Z, and only then calls waitpid. Save it as zombie_probe.py and run python3 zombie_probe.py as an ordinary user. Administrator privileges are not required.
import os
import time
from pathlib import Path
def state_of(pid):
try:
text = Path(f"/proc/{pid}/status").read_text()
except FileNotFoundError:
return "gone"
for line in text.splitlines():
if line.startswith("State:"):
return line.split()[1]
raise RuntimeError("Process state missing")
pid = os.fork()
if pid == 0:
os._exit(7)
reaped = False
try:
deadline = time.monotonic() + 3
while time.monotonic() < deadline:
state = state_of(pid)
if state == "Z":
break
time.sleep(0.02)
else:
raise RuntimeError("Zombie state not observed")
print(f"before_wait pid={pid} state={state}")
waited, status = os.waitpid(pid, 0)
reaped = True
code = os.waitstatus_to_exitcode(status)
assert waited == pid and code == 7
print(f"after_wait exit={code} state={state_of(pid)}")
finally:
if not reaped:
os.waitpid(pid, 0)
The expected result is state=Z first, followed by exit code 7 and removal of the original process's /proc entry. In an edge case where the PID is reused immediately, the later state read may see a new process. The primary evidence of successful reaping is that waitpid returned the intended child PID and expected exit code, not simply that a path disappeared.
The wait limit in this experiment is only a local test budget, not a service response commitment. If the script encounters an exception, it still attempts to reap the child so that testing the problem does not leave another uncollected exit status behind.
4. Fix the code paths that own child processes
For programs using Python's subprocess, creating a process object does not mean that the child will automatically be reaped promptly. Synchronous tasks should explicitly wait and check the exit code. For asynchronous tasks, the owner must continue tracking the child rather than creating it and immediately discarding the reference.
import subprocess
proc = subprocess.Popen(
["sleep", "1"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
returncode = proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.terminate()
try:
returncode = proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
returncode = proc.wait()
print(f"child_exit={returncode}")
This code demonstrates waiting after normal completion, a termination request, and a force-kill. The example covers only a direct child. If the task also creates grandchildren, you need a separate process-group or service-level shutdown strategy; terminating one PID cannot be assumed to terminate the entire process tree.
Two pitfalls with pipes and signal handling
Setting output to PIPE and then calling only wait can cause a deadlock when the pipe fills. Use communicate when collecting output, and choose file-backed output or controlled streaming reads according to the output volume rather than keeping an unlimited amount in memory.
Programs using SIGCHLD notifications must not assume that one signal corresponds to exactly one exited child. Reap in a nonblocking loop until no more children are available to reap. Also prevent multiple threads or modules from competing to collect the same child's exit status.
5. Validate the task lifecycle, not just a zero zombie count
The fix should cover three paths: normal exit, nonzero exit, and cancellation. Record the parent and child identities, exit code, and reaping result for each test. Run only a finite number of tests; do not create process pressure with an infinite loop.
Validation should include at least these checks:
- After a task finishes, the parent can accept the next task, and uncollected exit records do not keep accumulating.
- The timeout path completes both termination and waiting, rather than reporting success after merely sending a signal.
- A nonzero exit enters failure handling; successful reaping is not mistaken for successful task execution.
- Tasks that capture output do not hang because a pipe fills, and output size has an explicit limit.
- Active tasks have been drained before the parent restarts, and enough evidence is retained for review.
If the parent is a program you cannot modify, first confirm its version and the conditions needed to reproduce the problem, then arrange a controlled replacement or restart. When the parent exits, its children are usually taken over by an adopting process within the namespace. That process must still reap them correctly; reparenting alone is not a complete fix.
Ultimately, you need to demonstrate that every child created has a clearly designated recipient for its status, and that every exit path reaches a wait call. A zombie count of zero is only the outcome. Reliable operation depends on the parent continuing to reap its children correctly.
Frequently asked questions
Why does forcibly killing a zombie process not remove it?
A zombie has already exited. The kernel retains its exit record for the parent, which must collect it through a wait-family call. Sending another termination signal does not perform that collection.
Should the parent be restarted as soon as a zombie appears?
No. Record PID, PPID, start time and the count over time first. If reaping is defective, fix the program and restart the parent after draining its active work.
Dedicated AMD EPYC 7543P server, from $469/month