9.7. Investigating Stuck or Runaway Processes

Sooner or later a process will misbehave on a machine you administer: a backup wedged in the middle of the night, a server spawning children without end, a compile eating every CPU. This section is about the three situations that account for most such incidents - a task the signals cannot reach, a process table full of the dead, and a load number that says one thing while the screen says another - and about containing a runaway before killing it.

9.7.1. Uninterruptible Sleep, Zombies, and Load Average

The load average is the classic first glance at a machine's health, and it is easy to misread in both directions. It lives in /proc/loadavg:

$ cat /proc/loadavg
0.63 0.55 0.42 1/108 10337

The first three numbers are the count of runnable plus uninterruptible tasks, averaged over 1, 5, and 15 minutes with exponential decay - 0.63 tasks waiting for this 2-CPU machine, comfortably idle. The fourth field is running/total scheduling entities, the last the most recent PID. Load must be read against the CPU count: 2.0 on this machine means "both CPUs have work whenever they want it"; 4.0 means tasks are queuing. Now load the machine with two CPU hogs and look again while they run:

$ stress-ng --cpu 2 --timeout 6s --metrics-brief >load.out 2>&1 &
$ sleep 3
$ cat /proc/loadavg
0.74 0.58 0.43 3/112 10359
$ wait
$ tail -n 8 load.out
stress-ng: metrc: [10355] stressor       bogo ops real time  usr time  sys time   bogo ops/s     bogo ops/s
stress-ng: metrc: [10355]                           (secs)    (secs)    (secs)   (real time) (usr+sys time)
stress-ng: metrc: [10355] cpu               15861      6.00     11.98      0.01      2642.97        1322.64
stress-ng: info:  [10355] skipped: 0
stress-ng: info:  [10355] passed: 2: cpu (2)
stress-ng: info:  [10355] failed: 0
stress-ng: info:  [10355] metrics untrustworthy: 0
stress-ng: info:  [10355] successful run completed in 6.01 secs

The hogs ran the full six seconds - the summary shows 11.98 s of user CPU, both workers flat out. But the load average only crept from 0.63 to 0.74, because the kernel samples the counts every five seconds and the averages decay slowly; a three-second burst barely moves even the 1-minute figure. The lesson cuts both ways: a sustained load of 0.74 on a busy 2-CPU machine is genuinely fine, but a short spike will not appear in loadavg at all - for live contention, vmstat's r column (Section 9.5.1) counts runnable tasks instantaneously. The second thing loadavg quietly includes is tasks in uninterruptible sleep, which is why a hung NFS mount can show a load of 8.0 with the CPUs idle - the number counts waiting, not just working.

A zombie is a process that has already exited but whose parent has not collected its exit status with wait(). The kernel keeps the PID slot and the status - nothing else, no memory, no CPU - until the parent asks or dies. This fixture leaves one; save it as zombie_maker.py:

#!/usr/bin/env python3
"""Leave one exited child unreaped so it appears as a zombie."""
import os
import sys
import time

pid = os.fork()
if pid == 0:
    os._exit(0)
print(f"child={pid} parent={os.getpid()}", flush=True)
time.sleep(int(sys.argv[1]) if len(sys.argv) > 1 else 20)
os.waitpid(pid, 0)

The child exits instantly; the parent prints both PIDs and then sleeps without reaping. Run it and look at the parent's children:

$ rm -f zombie.out
$ nohup ./zombie_maker.py 120 > zombie.out 2>&1 &
$ zp=$!
$ sleep 1
$ cat zombie.out
child=11307 parent=11305
$ ps -o pid,ppid,stat,cmd --ppid $zp
    PID    PPID STAT CMD
 11307   11305 Z    [python3] <defunct>

The setup lines are silent as usual; cat shows the pair, and the child appears in state Z, marked <defunct> - dead, held open by its sleeping parent. Zombies are harmless in ones and threes; they matter when a buggy parent leaks them by the thousand, because each holds a PID. The fix is always the parent, and here killing the parent proves it:

$ kill -TERM $zp
$ sleep 1
$ ps -o pid,ppid,stat,cmd --ppid $zp
    PID    PPID STAT CMD
$ echo ps-exit=$?
ps-exit=1

The parent died; the zombie was re-parented to systemd, which reaped it immediately; ps finds no children and exits 1. If the parent cannot be killed, the honest answer is that the zombie cannot be removed either - fix or restart the parent.

The state that brings pages like this one is D, uninterruptible sleep. This demonstration produces a real one without breaking anything: freezing a filesystem with fsfreeze blocks every write to it - the same operation used to take consistent snapshots (Chapter 12). Warning: while /mnt/io-lab is frozen, every write to it blocks, so freeze it only while you control what runs. In the root shell:

# fsfreeze -f /mnt/io-lab

Silent - the filesystem is now frozen. From john's shell, start a write to it:

$ cd /mnt/io-lab/workspace
$ dd if=/dev/zero of=frozen.bin bs=1M count=1 status=none &

The dd starts and blocks. Back in the root shell, find it and look at its state:

# ps -eo pid,stat,wchan:20,cmd | grep "dd if=/dev/zero of=frozen.bin" | grep -v grep
  10446 S    do_wait              bash -lc cd /mnt/io-lab/workspace && dd if=/dev/zero of=frozen.bin bs=1M count=1 status=none &
  10447 D    percpu_rwsem_wait    dd if=/dev/zero of=frozen.bin bs=1M count=1 status=none

The pipeline runs three stages: ps lists everything, the first grep keeps the lines naming our write, and grep -v grep discards the grep process itself (which otherwise matches its own pattern). Two lines remain. The dd - PID 10447 - is in state D, waiting on percpu_rwsem_wait, the frozen filesystem's internal lock. Its parent shell - the command line shown is simply however the write was started, a bash -lc ... wrapper in the recorded session - waits in do_wait, a normal interruptible wait for a child. In this state kill -9 10447 would be delivered and pended: SIGKILL acts when the task next runs, and it cannot run until the write completes. A task wedged in D for minutes usually means the storage underneath it is failing or unreachable - a dying disk, a hung NFS server, or, here, an administrator holding the freeze. Release it:

# fsfreeze -u /mnt/io-lab
# sleep 1
# ps -eo pid,stat,cmd | grep "dd if=/dev/zero of=frozen.bin" | grep -v grep || echo "dd finished after thaw"
dd finished after thaw

fsfreeze -u thaws the filesystem; the write completes and the dd is gone - the || branch runs because grep found nothing. For a D-state task you did not create yourself, the same reading applies: identify the wait (wchan, or cat /proc/<pid>/stack as root), check the device with iostat and the journal for driver errors, and fix the underlying storage - the process will die on its own the moment its I/O completes.

9.7.2. Inspecting System Calls and Process Waits

When a process is alive but doing nothing, the answer to "what is it waiting for?" is in its system calls. strace prints them as they happen; attaching to a running process needs root unless it is your own recent child. Start a sleep as john and record its PID:

$ nohup sleep 120 >/dev/null 2>&1 &
$ echo $! > traced.pid
$ cat traced.pid
10474

Then, in the root shell, attach:

# strace -p 10474
strace: Process 10474 attached
restart_syscall(<... resuming interrupted clock_nanosleep ...>strace: Process 10474 detached
 <detached ...>

The transcript shows the attachment, one line of evidence, and the detachment - the captured run was stopped after two seconds by an external timeout, and an interactive strace ends the same way when you interrupt it with Ctrl+C; the exact placement of the detach notice depends on when the interrupt lands, and here it appended to the still-unfinished syscall line. That single line is the whole answer anyway: the sleep is inside clock_nanosleep, resumed after the ptrace interruption (restart_syscall), exactly where a sleep 120 should be. Reading a strace is mostly learning a few call names:

Call seen The task is waiting for
clock_nanosleep, restart_syscall A timer - sleeping on purpose.
futex(...) A lock held by another thread.
read(...) on a socket or pipe Data from the network or a child.
epoll_wait, poll(...) Any of many file descriptors - an event loop.
wait4(...) A child process to exit.
Option Description
-p PID Attach to a running process (as root for others' processes).
-f Follow child processes as they are created.
-e expr Trace only selected calls, e.g. -e trace=network.
-c Count calls and time instead of printing them; run to completion, then summarize.
-o file Write the trace to a file instead of the terminal.

strace -c -p PID in particular gives a coarse answer ("almost all its time is in read") with much less noise than a live trace. The cheaper kernel view is wchan - the kernel function the task last slept in:

# cat /proc/10474/wchan; echo
do_syscall_64
# ps -o pid,stat,cmd -p 10474
    PID STAT CMD
  10474 S    sleep 120

The echo supplies the newline; cat of wchan does not add one. Here wchan reports do_syscall_64 - the syscall entry point, which is true of almost every sleeping task on a modern kernel and therefore says little; strace showed the actual call. What wchan gives you for nothing is its value in the D-state case, where the specific kernel wait (percpu_rwsem_wait in the frozen-write demo) names the subsystem involved. Together, ps for the state, strace for the call, and wchan for the kernel-side wait answer "what is it waiting for?" for nearly any process on the system.

9.7.3. Containing a Workload Before Terminating It

A runaway workload puts the administrator in a race: everything you want to do - inspect it, decide about it, warn its users - competes with the process consuming the machine. Cgroups turn that race into a procedure, because a workload in a cgroup can be frozen - stopped exactly where it is, in memory, without killing it - while you look. The kernel's freezer suspends every task in the cgroup; nothing it holds is released, sockets stay open, files stay held; the workload simply cannot run.

The demonstration uses a deliberately unbounded CPU load inside a transient unit. Its quota is set to the whole machine, so the containment, not the quota, is what stops it. In the root shell:

# systemd-run --unit=handbook-runaway --slice=handbook.slice -p CPUQuota=200% stress-ng --cpu 1 --timeout 60s
Running as unit: handbook-runaway.service; invocation ID: 398812d8dc8d4285a6c01cc95d99b07d
# systemctl show handbook-runaway -p MainPID -p ActiveState -p SubState
MainPID=10555
ActiveState=active
SubState=running

One CPU hog, running, PID 10555 - identified before anything is done to it. Now freeze it:

# systemctl freeze handbook-runaway
# systemctl show handbook-runaway -p ActiveState -p SubState -p FreezerState
ActiveState=active
FreezerState=frozen
SubState=running
# p=$(systemctl show handbook-runaway -p MainPID --value)
# ps -o pid,stat,cmd -p $p
    PID STAT CMD
  10555 SLs  /usr/bin/stress-ng --cpu 1 --timeout 60s

systemctl freeze prints nothing; the verification is the property pair: the unit is still active/running, but its FreezerState is frozen - the tasks will not be scheduled. The ps line shows the task as SLs - sleeping, plus letters recording that this process has pages locked in memory and is a session leader; the freezer's effect is in the cgroup state, not in STAT. This is the moment to investigate at leisure: attach strace, check /proc/10555/limits and the unit's memory accounting, look at what files it holds through /proc/10555/fd - the workload cannot move while frozen. If the verdict is "keep it", one command resumes it:

# systemctl thaw handbook-runaway
# systemctl show handbook-runaway -p FreezerState
FreezerState=running

Thawed, it would run out its sixty seconds. The other verdict ends it:

# systemctl kill --signal=SIGKILL handbook-runaway
# systemctl is-active handbook-runaway
failed

systemctl kill --signal=SIGKILL delivers the signal to every process in the unit's cgroup - no hunting for children - and is-active reports failed (with exit status 3, as Chapter 8 covered) because the main process was killed. SIGKILL is the last step of the ladder, after SIGTERM has had its chance; freezing first means the TERM step is also calm, because the workload cannot race the signal.

Assembled, the procedure for the next runaway - whatever it is:

  1. Identify it: top or ps for the CPU and memory leaders, systemctl status if it belongs to a unit, /proc/<pid>/fd for what it holds.
  2. Contain it: systemctl freeze UNIT if it is in a cgroup - which on a systemd system, it is - or kill -STOP PID for a single process outside one.
  3. Inspect it: strace -p PID, /proc/<pid>/limits, the unit's MemoryCurrent and TasksCurrent, the journal.
  4. Terminate in order: kill -TERM, wait, kill -KILL - or the systemctl kill forms for a unit.
  5. Verify: systemctl is-active, ps, and clean up the failed unit with systemctl reset-failed once the journal no longer needs it.

The whole containment - freeze, verify, then thaw or kill - was a handful of commands in this demonstration, and every mechanism in it came from this chapter: cgroup placement from Chapter 8 and Section 9.6.2, the quota that kept the demo bounded from Section 9.3.6, the signal semantics from Section 9.2.1, and the state letters from Section 9.1.1. What the administrator adds is the order of operations - freeze, look, then kill.

The resources a process claims are schedulers' and cgroups' business, and the tools in this chapter read and set all of them interactively. Two kinds of work follow naturally: running the same tasks on a schedule without an administrator present, which is Chapter 10, and watching the counters continuously so that the runaway is caught by a threshold instead of a phone call, which is Chapter 28.