Overview and What You Will Learn
A Linux process is a running instance of a program with its own PID, memory, open files, and state. You inspect processes with ps, top, and /proc, and you control them by sending signals with kill. Knowing which tool answers which question is what lets you find a runaway process in seconds.
By the end of this lab you will:
- Read
psandtopoutput, including memory and load figures - Explain the five main process states and spot zombie and D-state processes
- Stop a process gracefully with SIGTERM and escalate to SIGKILL only when needed
- Change CPU and disk priority with
nice,renice, andionice - Run long jobs in the background so they survive a closed terminal
- Read live process data from
/proc
Why This Matters in Production
Process problems cause two kinds of incidents: a runaway process that uses all the CPU or memory until the server stops responding, and leaked zombie or stuck processes that pile up until the system cannot start new ones. Both are visible in a few commands, long before the page escalates.
Teams that run latency-sensitive workloads, such as those at Zerodha and Cloudflare, depend on graceful shutdown so that a deploy or restart does not drop in-flight requests or leave half-written state behind.
Core Principles
Every process is in one state at a time. The state tells you whether a process is working, waiting, paused, hung on I/O, or finished and waiting to be reaped.
| State | Meaning | What to do |
|---|---|---|
R |
Running or ready to run | Normal. Many in R means CPU pressure. |
S |
Sleeping, can be interrupted | Normal for idle services |
D |
Uninterruptible sleep, usually disk or NFS | Cannot be killed. Fix the I/O problem. |
T |
Stopped by SIGSTOP or Ctrl+Z | Resume with SIGCONT |
Z |
Zombie: exited, parent has not collected it | Fix or restart the parent |
Reading ps aux:
USER PID %CPU %MEM VSZ RSS STAT START TIME COMMANDroot 1 0.0 0.1 168000 13000 Ss Jan01 0:05 /sbin/initwww-data 892 1.2 0.8 512000 80000 S 10:00 0:12 nginx: workerpayment 1350 45.3 2.1 1200000 210000 Rl 10:05 1:23 node index.jsroot 1401 0.0 0.0 0 0 Z 10:10 0:00 [cleanup] <defunct>VSZ and RSS are in kilobytes. VSZ is all address space the process has mapped, RSS is the RAM it is actually holding. STAT adds flags to the state: s session leader, l multi-threaded, + foreground, < high priority, N low priority.
RememberRSS is the figure to trust for memory use. A process with a 4 GB VSZ and a 200 MB RSS is using about 200 MB of physical memory.
Detailed Step-by-Step Practical Lab
Milestone 1: How to Snapshot Running Processes with ps and pgrep
ps auxps -ef # Tree view, which shows parent and child relationshipsps --forest -eo pid,ppid,user,stat,cmdpstree -p # Top consumersps aux --sort=-%cpu | head -15ps aux --sort=-%mem | head -15 # Choose your own columns for one processps -p 1350 -o pid,ppid,user,%cpu,%mem,rss,stat,etime,cmd # Find processes by name without matching the search command itselfpgrep -a nginxpgrep -u www-data -a nginx # Threads of a processps -L -p 1350 -o pid,tid,pcpu,stat,commTip
ps aux | grep nginxalso lists thegrepprocess itself.pgrep -a nginxprints the PID and full command line without that noise, and confirms you have the right target before you send a signal.
Milestone 2: How to Monitor Processes in Real Time with top and htop
topUseful keys inside top: P sorts by CPU, M by memory, 1 shows each CPU, c shows full command lines, k sends a signal, r changes priority, and q quits.
top - 10:23:45 up 15 days, load average: 1.23, 0.87, 0.65Tasks: 245 total, 2 running, 243 sleeping, 0 stopped, 0 zombie%Cpu(s): 12.3 us, 2.1 sy, 0.0 ni, 84.1 id, 1.2 wa, 0.0 hi, 0.3 siLoad average is the number of runnable plus uninterruptible tasks, averaged over 1, 5, and 15 minutes. Compare it with the CPU count from nproc: a load of 8 is fine on 16 cores and a problem on 2. A consistently high wa (I/O wait) points to a disk or network storage bottleneck.
# Non-interactive snapshot for scripts and ticketstop -b -n 1 -o %MEM | head -20 # htop: colour bars, mouse, F6 to sort, F9 to send a signal, Space to tagsudo apt install htophtopMilestone 3: How to Spot Zombie and D-State Processes
Create a zombie on purpose. The subshell starts a short-lived child, then replaces itself with sleep and never waits for it:
bash -c 'sleep 1 & exec sleep 60' &sleep 3ps -eo pid,ppid,stat,cmd | awk '$3 ~ /^Z/'# 2911 2910 Z [sleep] <defunct>A zombie is already dead, so kill -9 has no effect on it. It disappears when its parent calls wait() or exits, after which init adopts and reaps it. Find the parent from the PPID column and fix or restart that program.
# Kill the parent to clean up the zombie (here, the sleep 60 process)kill 2910 # Processes stuck in uninterruptible sleep, and what kernel function they wait inps -eo pid,stat,wchan:32,cmd | awk '$2 ~ /^D/' # How many processes and threads exist, versus the system limitps -e --no-headers | wc -lps -eL --no-headers | wc -lcat /proc/sys/kernel/pid_maxA few short-lived D entries are normal. Processes that stay in D for minutes usually mean a hung NFS mount, a failing disk, or an overloaded storage backend, and no signal will release them.
Milestone 4: How to Stop Processes with Signals
A signal is a small message the kernel delivers to a process. Most can be caught, which lets the program clean up. SIGKILL and SIGSTOP cannot be caught.
| Signal | Number | Typical use |
|---|---|---|
SIGTERM |
15 | Polite shutdown request, the default for kill |
SIGINT |
2 | Interrupt, what Ctrl+C sends |
SIGHUP |
1 | Reload configuration, if the program supports it |
SIGKILL |
9 | Immediate termination, cannot be caught |
SIGSTOP, SIGCONT |
19, 18 | Pause and resume (numbers shown are for x86 Linux) |
SIGUSR1, SIGUSR2 |
10, 12 | Application-defined, such as log rotation |
Create a worker that handles SIGTERM, then compare a graceful stop with a forced one:
cat > /tmp/worker.sh << 'EOF'#!/usr/bin/env bashcleanup() { echo "SIGTERM received, flushing and exiting"; rm -f /tmp/worker.lock; exit 0; }trap cleanup TERM INTtouch /tmp/worker.lockwhile true; do sleep 1; doneEOFchmod +x /tmp/worker.sh /tmp/worker.sh &WORKER_PID=$! kill -TERM "$WORKER_PID" # cleanup runs, lock file is removedls /tmp/worker.lock # No such file /tmp/worker.sh &kill -KILL $! # no cleanup is possiblels /tmp/worker.lock # stale lock file left behindThe trap runs once the current sleep 1 finishes, so expect up to a second of delay.
Use signal names rather than numbers, and check the target before you send:
kill -l # list signalspgrep -af 'node worker' # preview what would matchpkill -TERM -f 'node worker' # signal every matchkill -HUP "$(pidof nginx | awk '{print $1}')" # reload nginx master # Is it alive? Exit 0 means yes (1 means gone or not permitted)kill -0 1350 && echo alive # Signal a whole process group (note the minus sign)kill -TERM -- -2911Wrap the escalation in a helper so you never jump straight to SIGKILL:
stop_gracefully() { local pid="$1" timeout="${2:-30}" waited=0 kill -TERM "$pid" 2> /dev/null || return 0 while kill -0 "$pid" 2> /dev/null; do if (( waited >= timeout )); then echo "PID $pid ignored SIGTERM for ${timeout}s, sending SIGKILL" >&2 kill -KILL "$pid" return 0 fi sleep 1 waited=$((waited + 1)) done}Common MistakeReaching for
kill -9first. SIGKILL gives the program no chance to flush buffers, close database connections, release locks, or finish requests, and it can leave corrupt or stale state. Send SIGTERM, wait 10 to 30 seconds, and use SIGKILL only if the process ignores it.
SecurityRegular users can signal only their own processes. Root can signal any process. Use
sudo systemctl stop SERVICEfor managed services rather than killing the PID, so systemd does not simply restart it.
Milestone 5: How to Set CPU and Disk Priority with nice and ionice
nice values run from -20 (highest priority) to 19 (lowest), with 0 as the default. Only root can lower the value below 0.
# Start a backup at the lowest CPU and disk prioritynice -n 19 ionice -c3 pg_dump -U postgres orders > /backup/orders.sql # Change a running processrenice -n 10 -p 1350sudo renice -n -5 -p 892 # Checkps -o pid,ni,cmd -p 1350ionice -p 1350Priority only matters when processes compete for the CPU. A low-priority job on an idle machine still runs at full speed.
Milestone 6: How to Run and Manage Background Jobs
# Start in the background; $! holds its PID./long-running-script.sh &echo "started PID $!" # Job control in an interactive shelljobsfg %1 # bring to foreground# press Ctrl+Z to stop it, then:bg %1 # continue in the background # Survive a closed terminalnohup ./long-running-script.sh > /tmp/script.log 2>&1 & # Or detach an already-running job from the shell./server.sh &disown -h %1 # Start in a new session so a terminal hangup cannot reach itsetsid ./server.sh > /tmp/server.log 2>&1 < /dev/null & # Wait in a script./task-a.sh & PID_A=$!./task-b.sh & PID_B=$!wait "$PID_A" "$PID_B"For anything that must keep running and restart on failure, use a systemd unit or systemd-run rather than nohup:
sudo systemd-run --unit=reindex --property=MemoryMax=1G /opt/tools/reindex.shjournalctl -u reindex -fMilestone 7: How to Read Process Data from /proc
Every process has a directory /proc/PID/ that the kernel fills in on demand. You can read most of it as the process owner, and some files only as root.
PID=1350 cat /proc/$PID/cmdline | tr '\0' ' ' # full command linereadlink /proc/$PID/cwd # working directoryreadlink /proc/$PID/exe # real binary path # Memory and threads (values in kB)grep -E 'VmRSS|VmSize|Threads' /proc/$PID/status # Open file descriptors versus the limitsudo ls /proc/$PID/fd | wc -lgrep 'open files' /proc/$PID/limits # What the process has open and where it is connectedsudo lsof -p $PID | head -20sudo ss -tnp | grep "pid=$PID" # Environment (may contain secrets, readable only by the owner and root)sudo cat /proc/$PID/environ | tr '\0' '\n' | grep -E '^(NODE_ENV|PORT)=' # Watch memory over time to catch a leakwatch -n 5 "grep VmRSS /proc/$PID/status"If a process disappears without a trace, check whether the kernel killed it for running out of memory:
sudo dmesg -T | grep -i 'killed process'journalctl -k | grep -i 'out of memory'Production Best Practices & Common Pitfalls
Find the cause before you act, and stop things in the least destructive way that works.
- Identify the process with
psorpgrep -abefore sending any signal. - Send SIGTERM first, wait, then escalate to SIGKILL.
- Make your applications handle SIGTERM so deploys and restarts finish in-flight work.
- Use
systemctlfor services and signals for individual processes. - Track memory with RSS over time, not a single snapshot, to tell a leak from a spike.
- Run background maintenance with
niceandioniceso it does not starve the main service.
| Scenario | Wrong approach | Correct approach |
|---|---|---|
| Service not responding | kill -9 straight away |
kill -TERM, wait, then kill -9 |
| High CPU | Reboot the server | ps aux --sort=-%cpu, find and investigate |
| Zombie processes | Try to kill them | Fix or restart the parent |
| Process in D state | kill -9 |
Fix the storage or network I/O problem |
| Memory climbing | Restart and move on | Watch VmRSS, check logs and dmesg for OOM kills |
| Long job over SSH | Plain & |
nohup, setsid, tmux, or systemd-run |
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| All processes | ps aux |
| Top CPU | ps aux --sort=-%cpu | head -10 |
| Top memory | ps aux --sort=-%mem | head -10 |
| Find by name | pgrep -a NAME |
| Graceful stop | kill -TERM PID |
| Force stop | kill -KILL PID |
| Reload config | kill -HUP PID |
| Alive check | kill -0 PID |
| Open files | ls /proc/PID/fd | wc -l |
| Memory use | grep VmRSS /proc/PID/status |
| Detached job | nohup COMMAND > log.txt 2>&1 & |
| Symptom | First command | What to look for |
|---|---|---|
| Server slow | top -b -n 1 | head -15 |
Load versus nproc, high wa, top process |
| Cannot fork new processes | ps -eL --no-headers | wc -l |
Thread count near pid_max or a user limit |
Many <defunct> entries |
ps -eo pid,ppid,stat,cmd | awk '$3 ~ /^Z/' |
Common parent PID |
| Process will not die | ps -o pid,stat,wchan:32 -p PID |
D state and the kernel wait point |
| Process vanished | dmesg -T | grep -i 'killed process' |
OOM killer entry |
| Too many open files | grep 'open files' /proc/PID/limits |
Count in /proc/PID/fd near the limit |
TipTo find what a hung process is doing right now, run
sudo cat /proc/PID/stackfor the kernel stack orsudo strace -p PIDfor system calls. A process stuck inDoften shows the exact driver or filesystem call it is waiting in.
RememberSIGKILL and SIGSTOP are the only signals a process cannot catch or ignore. Everything else, including SIGTERM, can be handled by the program, which is why SIGTERM is the right first choice for a clean shutdown.