Processes: ps, top and friends

Linux · Essentials · 10 min

Finding what is running, what eats CPU or memory and what started what is everyday Linux work.

A process is a running instance of a program. Each has a PID, a parent (PPID), an owner, a state and its own memory. Processes form a tree: PID 1 (systemd on most systems) is the ancestor of everything, and every process is started by another one forking. $$ in bash is the shell's own PID.

Listing processes:

  • ps alone shows processes in your terminal; ps aux (BSD style) or ps -ef (System V style) show all of them,
  • ps -o pid,ppid,user,%cpu,%mem,stat,etime,cmd picks the columns,
  • ps -ef --forest or pstree show the parent/child tree,
  • pgrep -a name finds PIDs by name, pidof prog by exact program name.

top (or the friendlier htop) shows a live view sorted by CPU; in top, press M to sort by memory, P for CPU, k to kill and q to quit. The header shows uptime, load average, task counts and memory.

Process states in the STAT column: R running or runnable, S sleeping (waiting for something, the normal state), D uninterruptible sleep (usually waiting on disk or network storage), T stopped, Z zombie (finished, but its parent has not collected the exit status yet). A few zombies are harmless; a growing number points to a buggy parent.

Example

echo $$                               # PID of this shell
ps                                    # processes of this terminal
ps aux | head -n 3                    # USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
ps -ef --forest | tail -n 5           # parent/child tree
ps -o pid,ppid,stat,etime,cmd -p $$   # chosen columns for one PID
pgrep -a sshd                         # PIDs and command lines by name
ps aux --sort=-%mem | head -n 5       # top memory users
top                                   # live view: M memory, P CPU, q quit

Remember

  • Each process has a PID, a parent and an owner; PID 1 is systemd
  • ps aux / ps -ef list everything; pgrep finds by name
  • STAT: R running, S sleeping, D waiting on I/O, Z zombie

Watch out for

  • Reading ps aux | grep nginx and counting the grep process itself as a match; use pgrep.

Check yourself

  1. What does a process in state D usually indicate?
  2. Which process is the ancestor of all others on a typical modern distribution?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man7.org/linux/man-pages/man1/ps.1.html