6.3 Process Monitoring: ps, top, free, watch, pgrep, pstree & uptime (103.5)
Key Takeaways
- Every Linux process carries a Process ID (PID), a Parent Process ID (PPID), user/group IDs, a controlling terminal (TTY), cumulative CPU time, and an execution state shown in the `STAT` column: `R` (Running), `S` (Interruptible Sleep), `D` (Uninterruptible Sleep/Disk I/O), `Z` (Zombie/Defunct), and `T` (Stopped/Traced), with modifiers such as `<` (high priority), `N` (low priority), and `+` (foreground group).
- The `ps` utility supports both UNIX syntax (`ps -ef`, with dashes) and BSD syntax (`ps aux`, without dashes), providing granular metrics including virtual memory (`VSZ`) and resident physical RAM (`RSS`).
- The `top` utility provides a dynamic real-time dashboard displaying system uptime, task states, CPU breakdown (us, sy, ni, id, wa, hi, si, st), memory usage, and interactive sorting keys (`M` for memory, `P` for CPU, `k` to kill).
- `pgrep` filters the active process table by pattern, name, user (`-u`), or full command line (`-f`), while `pstree` visualizes hierarchical process parentage originating at PID 1.
- free reports system-wide memory and its 'available' column (not 'free') is the true measure of memory pressure, while watch -n <sec> re-runs any snapshot command on an interval and -d highlights what changed.
6.3 Process Monitoring: ps, top, pgrep, pstree, uptime
Quick Summary: In Linux, every running program, background daemon, and worker thread operates as a process tracked by the kernel. Administrators inspect system performance, resource utilization, and application health using a standard diagnostic toolkit:
psprovides static process snapshots using UNIX (ps -ef) or BSD (ps aux) options;topprovides a dynamic real-time resource monitor;pgrepqueries processes by name or command-line regex;pstreediagrams process hierarchy trees rooted at PID 1; anduptimeassesses multi-core CPU load averages over 1, 5, and 15-minute intervals.
1. Process Lifecycle, Identifiers & Process States
A process is an instance of an executing program in memory with its own allocated virtual address space, file descriptor table, and security context.
Core Process Identifiers
- PID (Process ID): A unique unsigned integer assigned by the kernel to identify an active process. The first user-space process created during boot (
systemdor SysVinit) always receives PID 1. - PPID (Parent Process ID): The PID of the process that spawned this child process via the
fork()system call. When a parent process terminates before its children, the orphaned child processes are re-parented to PID 1. - UID / GID (User & Group IDs): The real and effective user/group credentials governing the process's filesystem and syscall permissions.
- TTY: The controlling terminal device (e.g.,
pts/0,tty1, or?for background daemons with no controlling terminal).
The Process State Model (STAT / S Column)
In ps and top output, the kernel reports the operational state of every process using single-letter codes:
| State Code | Name | Detailed Technical Description |
|---|---|---|
R | Running / Runnable | The process is either actively executing on a CPU core or waiting in the scheduler's run queue ready for execution. |
S | Interruptible Sleep | The process is paused waiting for an event, signal, timer, or I/O availability. It can be awakened immediately by signals. |
D | Uninterruptible Sleep | The process is waiting directly on hardware I/O (typically synchronous disk read/write or NFS network operations). Cannot be killed by any signal, including SIGKILL, until the hardware I/O operation finishes. |
Z | Zombie / Defunct | The process has terminated execution via exit(), but its parent process has not yet read its exit status via the wait() or waitpid() syscall. It holds no memory or CPU, only a slot in the kernel process table. |
T | Stopped / Traced | The process has been suspended by a job control signal (e.g., SIGSTOP, SIGTSTP via Ctrl+Z) or is being traced by a debugger (e.g., gdb, strace). |
Process State Modifiers
In BSD-style ps aux output, additional characters append to the primary state code:
<: High priority (has a negative niceness value, taking more CPU time).N: Low priority (has a positive niceness value, "nice" to other processes).s: Session leader (the process created the terminal session, e.g., a login shell).l: Multi-threaded process (cloned usingCLONE_THREAD).+: Member of the foreground process group in its controlling terminal.
Example STAT Strings in `ps aux`:
Ss --> Session leader in interruptible sleep (e.g., bash login shell)
R+ --> Process actively executing in the foreground (e.g., top, grep)
S<l --> Multi-threaded process with elevated real-time priority (e.g., audio server)
Z --> Zombie process awaiting parent collection
2. Snapshot Inspection with ps (UNIX vs. BSD Styles)
The ps (Process Status) utility dumps a static snapshot of active processes. The tool supports three distinct syntax conventions:
- UNIX (POSIX) Options: Prefixed with a single dash
-(e.g.,ps -ef,ps -e). - BSD Options: Used without any dashes (e.g.,
ps aux,ps ax). - GNU Long Options: Prefixed with two dashes
--(e.g.,ps --sort=-%cpu).
# 1. UNIX Standard Full Listing: ps -ef
$ ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 08:00 ? 00:00:02 /sbin/init
root 842 1 0 08:01 ? 00:00:00 /usr/sbin/sshd -D
admin 2415 842 0 09:15 pts/0 00:00:00 -bash
admin 3102 2415 0 10:22 pts/0 00:00:00 ps -ef
# 2. BSD User-Oriented Listing: ps aux
$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.1 168432 13420 ? Ss 08:00 0:02 /sbin/init
root 842 0.0 0.0 15812 7104 ? Ss 08:01 0:00 /usr/sbin/sshd -D
admin 2415 0.0 0.0 10856 5120 pts/0 Ss 09:15 0:00 -bash
admin 3105 0.0 0.0 11492 3480 pts/0 R+ 10:22 0:00 ps aux
Comparing Output Columns: UNIX vs. BSD
UNIX Column (ps -ef) | BSD Column (ps aux) | Technical Definition |
|---|---|---|
UID | USER | The user name or UID owning the process. |
PID | PID | Process ID. |
PPID | — | Parent Process ID (Crucial for identifying rogue parent daemons). |
C | %CPU | Integer processor utilization metric vs. floating-point CPU percentage. |
| — | %MEM | Percentage of physical RAM (Resident Set Size) consumed. |
| — | VSZ | Virtual Memory Size (in KiB): Total memory allocated, including shared libs, mapped files, and uncommitted pages. |
| — | RSS | Resident Set Size (in KiB): Exact non-swapped physical RAM currently held by the process. |
TTY | TTY | Controlling terminal (? indicates detached background daemon). |
| — | STAT | Process state and modifier flags (R, S, D, Z, T, +, <, N). |
STIME | START | Starting time or date of the process. |
TIME | TIME | Cumulative CPU execution time consumed by the process. |
CMD | COMMAND | Full executable path and command-line arguments. |
Advanced ps Querying & Sorting Examples
# Sort processes by memory consumption in descending order (highest first):
$ ps aux --sort=-%mem | head -n 10
# Sort processes by CPU consumption in descending order:
$ ps aux --sort=-%cpu | head -n 10
# Custom output formatting showing only PID, PPID, User, and Command:
$ ps -eo pid,ppid,user,stat,comm
# Filter processes for a specific user:
$ ps -u admin -f
3. Dynamic Real-Time Monitoring with top
The top program provides an interactive, real-time diagnostic dashboard that updates every 3.0 seconds by default.
top - 10:30:15 up 2 days, 3:14, 2 users, load average: 0.15, 0.08, 0.02
Tasks: 185 total, 1 running, 184 sleeping, 0 stopped, 0 zombie
%Cpu(s): 2.3 us, 1.0 sy, 0.0 ni, 96.2 id, 0.3 wa, 0.1 hi, 0.1 si, 0.0 st
MiB Mem : 7952.4 total, 2145.1 free, 3210.8 used, 2596.5 buff/cache
MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 4421.2 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1420 admin 20 0 852412 184210 45120 S 4.5 2.3 1:12.45 node
842 root 20 0 15812 7104 5980 S 0.0 0.1 0:00.12 sshd
Top Header Metrics Breakdown
- System Uptime & Load Average (Line 1): Current system clock, elapsed uptime, logged-in user count, and exponential moving load averages over 1, 5, and 15 minutes.
- Tasks Summary (Line 2): Breakdown of total system processes across running, sleeping, stopped, and zombie states.
- CPU Utilization Breakdown (Line 3):
us(User): Time spent running un-niced user-space processes.sy(System): Time spent running kernel-space system routines and syscalls.ni(Nice): Time spent running niced (low-priority) user processes.id(Idle): Percentage of time CPU is idle and unutilized.wa(I/O Wait): Time CPU spent waiting for disk/storage I/O completion. Highwaindicates disk bottlenecks.hi/si(Hardware / Software IRQ): Time servicing hardware and software interrupts.st(Steal Time): CPU cycles stolen by the hypervisor in virtualized environments.
- Memory Lines (Lines 4 & 5): Physical RAM and Swap breakdown showing Total, Free, Used, Buffers/Cache, and
avail Mem(memory available for starting new applications without swapping).
Interactive Keystrokes in top
| Keystroke | Operational Action & Exam Purpose |
|---|---|
q | Quit the top program immediately. |
h or ? | Display the interactive Help screen. |
k | Kill a process: Prompts for PID and signal number (defaults to 15 / SIGTERM). |
r | Renice a process: Prompts for PID and new niceness value. |
M | Sort process list by Memory utilization (%MEM) descending. |
P | Sort process list by CPU utilization (%CPU) descending (default view). |
T | Sort process list by Cumulative Execution Time (TIME+). |
N | Sort process list numerically by PID. |
1 | Toggle between aggregated CPU view and individual per-core CPU breakdown. |
u | Filter displayed processes by a specific Username. |
z | Toggle color display mode on/off. |
W | Write current display settings and sort orders to ~/.toprc for persistent defaults. |
d or s | Change screen refresh update interval delay (in seconds). |
4. Targeted Process Querying with pgrep
The pgrep utility looks through the currently running processes and lists the process IDs (PIDs) matching specified selection criteria (e.g., regex patterns, usernames):
# List PIDs of all processes named 'nginx'
$ pgrep nginx
1042
1043
1044
Key pgrep Flags for LPIC-1
| Flag | Long Option | Functional Purpose |
|---|---|---|
-l | --list-name | Lists the process name alongside the numeric PID. |
-a | --list-full | Lists the full command line with all arguments alongside the PID. |
-f | --full | Matches the search pattern against the complete command line, not just the binary name. |
-u <user> | --euid <user> | Matches processes belonging to the specified effective user name or UID. |
-U <user> | --uid <user> | Matches processes belonging to the specified real user name or UID. |
-c | --count | Suppresses PIDs and prints only the total count of matching processes. |
-n | --newest | Selects only the newest (most recently started) matching process. |
-o | --oldest | Selects only the oldest (least recently started) matching process. |
-x | --exact | Requires an exact match of the process name. |
# Find processes matching 'python' and print full arguments:
$ pgrep -a python
4120 /usr/bin/python3 /opt/app/worker.py --threads=4
# Count how many worker processes are running for user www-data:
$ pgrep -u www-data -c
8
5. Visualizing Process Trees with pstree & System Load with uptime
pstree
pstree displays the running processes as a tree structure, visually showing parent-child inheritance hierarchies rooted at PID 1 (systemd or init):
$ pstree -p
systemd(1)─┬─cron(820)
├─sshd(842)───sshd(2410)───bash(2415)───pstree(3201)
├─systemd-journal(412)
└─systemd-udevd(450)
Essential pstree Flags
-p: Displays Process IDs (PIDs) in parentheses next to each process name.-u: Shows user transitions when a child process runs under a different UID than its parent.-a: Displays command-line arguments for each process.-h: Highlights the current process and its ancestors.
uptime and System Load Averages
The uptime utility outputs a single line summarizing system availability:
$ uptime
10:45:02 up 14 days, 2:30, 3 users, load average: 1.25, 0.85, 0.40
Interpreting System Load Average
The three numbers represent the average number of processes in a Runnable (R) or Uninterruptible Disk Sleep (D) state over the past 1, 5, and 15 minutes.
- On a single-core system, a load average of
1.0means the CPU is at 100% capacity. - On a 4-core system, a load average of
4.0represents 100% saturation. A load average of1.25indicates that the 4-core system is running at roughly 1.25 / 4 = 31.25% utilization.
6. Memory Snapshots with free
free is listed in the 103.5 Terms and Utilities alongside ps, top and uptime, and it answers the one question ps cannot: how much memory does the system as a whole have left? It reads /proc/meminfo and prints a two-line (or three-line, with swap) summary.
$ free -h
total used free shared buff/cache available
Mem: 7.8Gi 3.1Gi 2.1Gi 210Mi 2.5Gi 4.3Gi
Swap: 2.0Gi 0B 2.0Gi
| Column | Meaning |
|---|---|
| total | Installed RAM visible to the kernel (slightly less than the sticker figure — firmware reserves some) |
| used | total − free − buff/cache |
| free | Completely unallocated memory |
| shared | Memory used by tmpfs filesystems (/dev/shm, /run) |
| buff/cache | Page cache and kernel buffers — reclaimable on demand |
| available | The number that matters: how much a new application could allocate without swapping |
| Flag | Effect |
|---|---|
-h | Human-readable units (Gi, Mi) |
-m / -g | Force mebibytes / gibibytes |
-b / -k | Force bytes / kibibytes (kibibytes is the default) |
-t | Add a Total: row summing RAM and swap |
-s <sec> | Repeat continuously every N seconds |
-c <n> | With -s, stop after N samples |
Exam Trap — "free" Looks Alarmingly Low: A healthy long-running Linux server shows very little in the free column, because the kernel uses every otherwise-idle page for the disk cache. That is correct behaviour, not a leak. Read available, not free, to judge memory pressure. Genuine exhaustion shows up as growing Swap: used plus rising
si/socolumns invmstat.
7. Repeating a Command with watch
watch also appears in the 103.5 Terms and Utilities. It re-runs a command on a fixed interval and redraws its output in place, giving you a live view of any tool that only produces a snapshot — free, ps, df, lsblk, swapon, or a file in /proc.
# Default interval is 2 seconds
$ watch free -h
# Refresh every 5 seconds
$ watch -n 5 'ps -eo pid,comm,%cpu --sort=-%cpu | head -10'
# Highlight what changed since the previous refresh
$ watch -d -n 1 'cat /proc/loadavg'
# Exit automatically as soon as the command's output changes
$ watch -g lsblk
| Flag | Effect |
|---|---|
-n <sec> | Interval between runs (default 2) |
-d (--differences) | Highlight characters that changed since the last run |
-t (--no-title) | Suppress the header line showing interval, command and clock |
-g (--chgexit) | Exit as soon as the output differs from the first run |
-e (--errexit) | Freeze and exit if the command returns non-zero |
-x | Pass the command to exec rather than to a shell |
Exam Rule: Quote any pipeline you hand to
watch. Without quotes, the shell applies the pipe towatchitself —watch ps | headpipes watch's output intoheadinstead of repeating the whole pipeline. PressCtrl+Cto stop;watchruns until interrupted unless-gor-eis given.
While reviewing ps aux output, an administrator observes a process with a state of Z in the STAT column. What does this process state indicate?
Which interactive keystroke within the top command will immediately sort the active process list by physical memory consumption (%MEM) in descending order?
An administrator needs to locate the PID of a running Python daemon that was started as python3 /opt/services/sync_worker.py --interval=30. Running pgrep sync_worker returns no results. Which pgrep flag will search the entire command line with arguments?