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:
psalone shows processes in your terminal;ps aux(BSD style) orps -ef(System V style) show all of them,ps -o pid,ppid,user,%cpu,%mem,stat,etime,cmdpicks the columns,ps -ef --forestorpstreeshow the parent/child tree,pgrep -a namefinds PIDs by name,pidof progby 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 quitRemember
- 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 nginxand counting the grep process itself as a match; use pgrep.