Skip to main content

Managing Linux Processes with ps, top, and Signals

Inspect and control Linux processes with ps, top, htop, kill, and signals. Spot zombies and D-state hangs, stop services gracefully, and read /proc.

30 Terms

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 ps and top output, 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, and ionice
  • 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.

stateDiagram-v2 [*] --> R: fork R --> S: waits for event S --> R: event arrives S --> D: blocking I/O D --> R: I/O completes R --> T: SIGSTOP T --> R: SIGCONT R --> Z: exits Z --> [*]: parent calls wait
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:

TEXT
USER PID %CPU %MEM VSZ RSS STAT START TIME COMMAND
root 1 0.0 0.1 168000 13000 Ss Jan01 0:05 /sbin/init
www-data 892 1.2 0.8 512000 80000 S 10:00 0:12 nginx: worker
payment 1350 45.3 2.1 1200000 210000 Rl 10:05 1:23 node index.js
root 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.

Remember

RSS 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
Bash
ps aux
ps -ef
# Tree view, which shows parent and child relationships
ps --forest -eo pid,ppid,user,stat,cmd
pstree -p
# Top consumers
ps aux --sort=-%cpu | head -15
ps aux --sort=-%mem | head -15
# Choose your own columns for one process
ps -p 1350 -o pid,ppid,user,%cpu,%mem,rss,stat,etime,cmd
# Find processes by name without matching the search command itself
pgrep -a nginx
pgrep -u www-data -a nginx
# Threads of a process
ps -L -p 1350 -o pid,tid,pcpu,stat,comm
Tip

ps aux | grep nginx also lists the grep process itself. pgrep -a nginx prints 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
Bash
top

Useful 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.

TEXT
top - 10:23:45 up 15 days, load average: 1.23, 0.87, 0.65
Tasks: 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 si

Load 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.

Bash
# Non-interactive snapshot for scripts and tickets
top -b -n 1 -o %MEM | head -20
# htop: colour bars, mouse, F6 to sort, F9 to send a signal, Space to tag
sudo apt install htop
htop
Milestone 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
bash -c 'sleep 1 & exec sleep 60' &
sleep 3
ps -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.

Bash
# 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 in
ps -eo pid,stat,wchan:32,cmd | awk '$2 ~ /^D/'
# How many processes and threads exist, versus the system limit
ps -e --no-headers | wc -l
ps -eL --no-headers | wc -l
cat /proc/sys/kernel/pid_max

A 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:

Bash
cat > /tmp/worker.sh << 'EOF'
#!/usr/bin/env bash
cleanup() { echo "SIGTERM received, flushing and exiting"; rm -f /tmp/worker.lock; exit 0; }
trap cleanup TERM INT
touch /tmp/worker.lock
while true; do sleep 1; done
EOF
chmod +x /tmp/worker.sh
/tmp/worker.sh &
WORKER_PID=$!
kill -TERM "$WORKER_PID" # cleanup runs, lock file is removed
ls /tmp/worker.lock # No such file
/tmp/worker.sh &
kill -KILL $! # no cleanup is possible
ls /tmp/worker.lock # stale lock file left behind

The 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:

Bash
kill -l # list signals
pgrep -af 'node worker' # preview what would match
pkill -TERM -f 'node worker' # signal every match
kill -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 -- -2911

Wrap the escalation in a helper so you never jump straight to SIGKILL:

Bash
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 Mistake

Reaching for kill -9 first. 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.

Security

Regular users can signal only their own processes. Root can signal any process. Use sudo systemctl stop SERVICE for 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.

Bash
# Start a backup at the lowest CPU and disk priority
nice -n 19 ionice -c3 pg_dump -U postgres orders > /backup/orders.sql
# Change a running process
renice -n 10 -p 1350
sudo renice -n -5 -p 892
# Check
ps -o pid,ni,cmd -p 1350
ionice -p 1350

Priority 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
Bash
# Start in the background; $! holds its PID
./long-running-script.sh &
echo "started PID $!"
# Job control in an interactive shell
jobs
fg %1 # bring to foreground
# press Ctrl+Z to stop it, then:
bg %1 # continue in the background
# Survive a closed terminal
nohup ./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 it
setsid ./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:

Bash
sudo systemd-run --unit=reindex --property=MemoryMax=1G /opt/tools/reindex.sh
journalctl -u reindex -f
Milestone 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.

Bash
PID=1350
cat /proc/$PID/cmdline | tr '\0' ' ' # full command line
readlink /proc/$PID/cwd # working directory
readlink /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 limit
sudo ls /proc/$PID/fd | wc -l
grep 'open files' /proc/$PID/limits
# What the process has open and where it is connected
sudo lsof -p $PID | head -20
sudo 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 leak
watch -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:

Bash
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.

  1. Identify the process with ps or pgrep -a before sending any signal.
  2. Send SIGTERM first, wait, then escalate to SIGKILL.
  3. Make your applications handle SIGTERM so deploys and restarts finish in-flight work.
  4. Use systemctl for services and signals for individual processes.
  5. Track memory with RSS over time, not a single snapshot, to tell a leak from a spike.
  6. Run background maintenance with nice and ionice so 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
Tip

To find what a hung process is doing right now, run sudo cat /proc/PID/stack for the kernel stack or sudo strace -p PID for system calls. A process stuck in D often shows the exact driver or filesystem call it is waiting in.

Remember

SIGKILL 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.

Resources

Explore More in Linux Process and System Management

All 6 Topics

Frequently Asked Questions

Is Managing Linux Processes with ps, top, and Signals free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Managing Linux Processes with ps, top, and Signals topic cover?

Inspect and control Linux processes with ps, top, htop, kill, and signals. Spot zombies and D-state hangs, stop services gracefully, and read /proc.

Found a mistake, an outdated step or a broken link?