Diagnose and Remediate a Runaway Process on Linux
System DesignModel answerLast updated
Given a degraded production host, use top, ps, find, and kill to identify a CPU-hungry process, handle files with hostile names, and terminate it safely.
Scenario
A production server has triggered high-CPU alerts and the application partition is nearly full. You have an SSH session. No other team member is available. Your job is to investigate the problem, handle the log files that are eating disk space, and stop the offending process — all without disrupting healthy workloads running alongside it.
Walk through the following three phases, providing exact commands with flags and a rationale for each choice.
Phase 1 — Identify the Offending Process
- Use
topin a mode that is safe to pipe or log (non-interactive / batch mode), and explain how to get a meaningful CPU reading rather than a noisy first-sample artifact. - Follow up with a
pssnapshot that captures, for a specific PID: the parent PID, full untruncated command-line arguments, thread count, and absolute start time. - Explain what each of those fields tells you operationally (for example, why the parent PID matters before you decide to
kill).
Phase 2 — Locate and Handle Large Scratch Files
The process writes temporary logs to /var/log/app_scratch/. Filenames may include spaces, leading dashes, newlines, or other non-printable characters.
- Write a
findcommand that returns only regular files on that filesystem, larger than 500 MB, last modified within the past 60 minutes. - Show how to safely consume those results in a downstream command (disk-usage summary or archive) without breaking on any of those filename edge cases.
- Call out the classic trap: what happens to disk space if the process still has one of those files open when you delete it, and how do you recover?
Phase 3 — Stop the Process Without Making Things Worse
- Describe the step-by-step sequence to terminate the process, starting with the gentler option.
- Contrast
SIGTERMandSIGKILL: what can each signal do and not do, and why does jumping straight tokill -9turn a CPU incident into a potential data-integrity incident for stateful or I/O-heavy services? - Show how to poll for exit without false positives (zombies,
EPERM), re-verify the process's identity before escalating, and explain why PID alone is not a sufficient identifier.
What a Complete Answer Looks Like
For each phase, provide runnable bash commands (with flags explained), the reasoning behind your choices, and the failure modes you are actively avoiding. Signal semantics and safe filename handling should be explained in prose, not just implied by the code.
Hints
Hint 1
For a reliable CPU reading from top, one iteration samples over too short a window to be meaningful — run two iterations with a delay and read the second block. Batch mode (-b) makes the output pipeable without curses escape codes.
Hint 2
NUL (\0) is the only byte that cannot appear in a POSIX filepath. -print0 paired with xargs -0, du --files0-from=-, or tar --null is the only fully general way to pass arbitrary filenames between commands. Never use for f in $(find ...) or bare xargs without -0.
Hint 3
Before sending any signal, record the process's start time alongside its PID — the pair (PID, start time) is the true identity. After SIGTERM, poll with kill -0 in a timed loop rather than sleeping a fixed amount; but watch out: kill -0 succeeds on zombies, and fails with EPERM on a live process you don't own, which is not the same as 'exited'.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Idea
This scenario tests operational discipline more than flag memorization. The safe workflow has a clear shape: observe, snapshot, handle files defensively, escalate signals gradually, and verify identity before and after each action. Skipping any step converts a performance incident into a data-integrity or availability one.
Phase 1 — Process Inspection
Real-time view with top
Interactive top is not scriptable. Batch mode is:
top -b -n 2 -d 1 -o %CPU | tail -n +$(( $(top -b -n 1 | grep -n "PID" | cut -d: -f1) ))
A simpler, common form:
top -b -n 2 -d 1 | grep -A 20 "PID"
The -n 1 trap: the first iteration computes CPU over the tiny interval since top started, so every process looks near-zero. Running -n 2 -d 1 and reading the second block gives a one-second sample — still short, but representative enough to identify a runaway.
State column values worth knowing: R (running), S (interruptible sleep), D (uninterruptible — often blocked on disk I/O, unkillable with SIGTERM), Z (zombie — already dead, waiting on parent), T (stopped).
Snapshot with ps
PID=12345
ps -ww -o pid,ppid,user,stat,%cpu,%mem,nlwp,lstart,etimes,args -p "$PID"
| Field | Why it matters operationally |
|---|---|
ppid | If the parent is systemd or a supervisor, killing the child directly may just trigger Restart=always. Stop the unit instead: systemctl stop <unit>. |
nlwp | A high thread count means the process may own many kernel resources; abrupt termination leaves more to clean up. |
lstart / etimes | The absolute start time is half of the process's true identity. You'll use it to guard against PID recycling before escalating. |
args with -ww | Without -ww, ps silently truncates long command lines, hiding the actual invocation. |
Phase 2 — Finding and Handling Files with Hostile Names
The find command
find /var/log/app_scratch/ -xdev -type f -size +500M -mmin -60 -print0
-xdev: stay on the filesystem that is full; don't follow mounts elsewhere.-type f: regular files only — excludes symlinks, directories, FIFOs.-size +500M: strictly greater than 500 MiB. Note thatfindrounds sizes up to whole units, so a 500 MiB + 1 byte file matches.-mmin -60: content modified less than 60 minutes ago.-print0: terminates each path with a NUL byte instead of a newline. NUL is the only character that cannot appear in a path, making this safe against spaces, newlines, tabs, and leading dashes.
Consuming results safely
Disk-usage summary:
find /var/log/app_scratch/ -xdev -type f -size +500M -mmin -60 -print0 \
| du -ch --files0-from=- | sort -h
Archive to a different partition (critical: never write the archive to the full disk):
find /var/log/app_scratch/ -xdev -type f -size +500M -mmin -60 -print0 \
| tar --null -T - -czf /mnt/other_disk/scratch-$(date +%s).tar.gz
Using -exec … {} + is a safe alternative that avoids the pipe entirely:
find /var/log/app_scratch/ -xdev -type f -size +500M -mmin -60 -exec du -h -- {} +
The -- ends option parsing, so a file named -rf is treated as a filename, not a flag.
The deleted-but-open trap. rm only removes the directory entry (the name). If the running process still has the file open, the inode and its blocks remain allocated, and df still shows the space as used. You can spot these with:
lsof +L1 # files with link count 0 — unlinked but still open
To reclaim space without stopping the process, truncate the file in place:
: > "/var/log/app_scratch/some file with spaces"
This zeroes the file immediately, and the process keeps writing to the same file descriptor. The space is freed now rather than on process exit. Avoid this if the process reads its own log for rotation or health checks.
Common mistake: for f in $(find ...) word-splits on whitespace and will silently act on wrong paths. Same problem with bare find | xargs without -0.
Phase 3 — Graceful vs. Forced Termination
Why signal order matters
SIGTERM (15) is catchable. A well-written process uses its signal handler to flush write buffers and fsync, finish or roll back in-flight transactions, release advisory locks and remove pidfiles, close sockets so clients see a clean drain, and reap child processes.
SIGKILL (9) cannot be caught, blocked, or ignored — the kernel tears the process down immediately. What gets left behind: partially written or structurally corrupt files, stale lock files that block a restart, orphaned child processes, leaked shared-memory and IPC segments, and clients that see connection resets instead of a graceful close. For stateful or I/O-heavy services, kill -9 as a first move converts a CPU incident into a data-integrity incident.
The safe sequence
PID=12345
# 1. Record identity before touching anything.
START=$(awk '{print $22}' /proc/$PID/stat)
ps -o pid,lstart,args -p "$PID" # human-readable confirmation
# 2. Send SIGTERM and poll for exit with a 30-second timeout.
kill -TERM "$PID"
for i in $(seq 1 30); do
kill -0 "$PID" 2>/dev/null || { echo "Process $PID has exited."; break; }
sleep 1
done
# 3. If still alive, re-verify identity before escalating.
if [ -r /proc/$PID/stat ]; then
CURRENT=$(awk '{print $22}' /proc/$PID/stat)
if [ "$CURRENT" = "$START" ]; then
echo "Re-verified identity; sending SIGKILL."
kill -KILL "$PID"
else
echo "PID $PID has been recycled. Aborting."
fi
fi
Caveats on kill -0 and PID recycling
kill -0returns exit code 0 if the process exists and you have permission to signal it, regardless of whether it has exited into zombie state. A zombie passeskill -0but is already dead — check thestatfield in/proc/$PID/statforZbefore concluding the process is still running.kill -0fails withEPERMif the process is alive but owned by another user. Do not readEPERMas "exited."- PID alone is not a sufficient identifier: the kernel recycles PIDs. The pair (PID, start time) is the minimal reliable identity. A
pidfd(Linux 5.3+) closes the race entirely but requires a different API.
Supervisor edge case
If ps shows the parent is systemd (or another process manager), killing the child directly is likely futile:
systemctl stop <unit-name> # correct approach
This sends the signal through the unit's configured stop sequence and prevents automatic restart.
Complexity
| Operation | Cost |
|---|---|
find traversal | O(directory entries), one stat syscall each |
ps -e / top | O(number of processes on the system) |
| Kill + poll loop | At most timeout iterations, O(1) work per iteration |