9.1. Understanding Processes
A process is more than a running program image. At any instant it has a kernel state (running, waiting, stopped, or exited), a parent that created it, a scheduling class that decides its share of the CPUs, and a table of open files that it inherited from its parent. The three subsections here build that picture: identity and states first, the standard inspection tools second, and the file-descriptor table third. Later sections change what a process gets; this one establishes how to see what it is.
9.1.1. Process IDs, Parentage, States, and Threads
Every process carries a process ID (PID), the PID of its parent (PPID), and
one parent only. On Debian, PID 1 is systemd, and every user process
descends from it - directly or through a chain of shells and daemons. Kernel
threads are the exception in appearance only: they are children of kthreadd
(PID 2), which the kernel starts at boot to host its own housekeeping
workers. Look at the process list sorted by PID:
$ ps -eo pid,ppid,stat,ni,comm --sort=pid | head -n 12
PID PPID STAT NI COMMAND
1 0 Ss 0 systemd
2 0 S 0 kthreadd
3 2 S 0 pool_workqueue_release
4 2 I< -20 kworker/R-kvfree_rcu_reclaim
5 2 I< -20 kworker/R-rcu_gp
6 2 I< -20 kworker/R-sync_wq
7 2 I< -20 kworker/R-slub_flushwq
8 2 I< -20 kworker/R-netns
10 2 I 0 kworker/0:1-cgroup_free
11 2 I< -20 kworker/0:0H-events_highpri
12 2 I 0 kworker/u8:0-ipv6_addrconf
The pipeline sends the full listing through head -n 12, which keeps the
first twelve lines and discards the rest. ps prints a header plus the
lowest-numbered processes: systemd with PPID 0 (started by the kernel
itself), kthreadd also with PPID 0, and kernel workers whose PPID is 2.
ni -20 on several workers is the kernel's own way of deprioritizing
background housekeeping, using the same nice value introduced in
Section 9.3.3.
ps option |
Description |
|---|---|
-e |
Select every process on the system. |
-o list |
Choose the output columns; pid,ppid,stat,ni,comm here. |
--sort=col |
Order the listing by a column, as in --sort=pid. |
-p PID |
Select one process by ID, as in ps -o ni -p 1234. |
--ppid PID |
Select the children of one process. |
-L |
List threads, adding LWP (thread) and NLWP (count) columns. |
The STAT column encodes the task's state as one capital letter plus
optional modifiers:
| Letter | State | Meaning |
|---|---|---|
R |
runnable/running | On a CPU or queued to get one. |
S |
sleeping | Waiting for an event, timer, or input; interruptible. |
D |
uninterruptible sleep | Blocked in the kernel, usually on I/O; signals wait until it returns. |
T |
stopped | Suspended by SIGSTOP or Ctrl+Z; resumed by SIGCONT. |
Z |
zombie | Exited; only the PID slot and exit status remain. |
I |
idle kernel thread | A kernel worker with nothing to do. |
Modifiers follow the letter: s marks a session leader (PID 1's Ss),
+ a foreground process, < a raised priority, N a lowered one, and l a
multithreaded task. A process moves between these states constantly; Figure
9.1 shows the whole lifecycle, including the two transitions administrators
actually get called about - a task stuck in D and a zombie waiting for its
parent.
Figure 9.1. Conceptual view of task states and parentage. A task blocked in uninterruptible sleep ignores nothing - it simply cannot run until the kernel operation finishes. An orphan is adopted by systemd and reaped there.
Threads make the picture one level deeper. A process is a container of one
or more threads, each with its own thread ID (TID) and stack but sharing
the process's memory and file descriptors; the kernel schedules threads, not
whole processes. ps -eLf lists every thread with LWP (the thread's kernel
ID, "light-weight process") and NLWP (how many threads its process has):
$ ps -eLf | head -n 10
UID PID PPID LWP C NLWP STIME TTY TIME CMD
root 1 0 1 0 1 19:20 ? 00:00:09 /sbin/init
root 2 0 2 0 1 19:20 ? 00:00:00 [kthreadd]
root 3 2 3 0 1 19:20 ? 00:00:00 [pool_workqueue_release]
root 4 2 4 0 1 19:20 ? 00:00:00 [kworker/R-kvfree_rcu_reclaim]
root 5 2 5 0 1 19:20 ? 00:00:00 [kworker/R-rcu_gp]
root 6 2 6 0 1 19:20 ? 00:00:00 [kworker/R-sync_wq]
root 7 2 7 0 1 19:20 ? 00:00:00 [kworker/R-slub_flushwq]
root 8 2 8 0 1 19:20 ? 00:00:00 [kworker/R-netns]
root 10 2 10 0 1 19:20 ? 00:00:00 [kworker/0:1-cgroup_free]
Everything shown so far is single-threaded (NLWP 1). TIME is accumulated
CPU time; /sbin/init is the program behind PID 1.
Parentage matters when a parent exits first. The kernel does not leave
children pointing at a dead PID: it re-parents them to systemd (PID 1), which
becomes responsible for reaping their exit statuses. That is what makes
nohup-style background work survive a logout. Create the chapter workspace
and demonstrate:
$ mkdir -p ~/debian-handbook/processes
The command is silent; change into the directory with
cd ~/debian-handbook/processes - the rest of the chapter works from there.
Now start a sleep process and record its PID:
$ nohup sleep 300 >/dev/null 2>&1 &
$ echo $! > sleeper.pid
Both lines produce no output. The first backgrounds sleep 300; nohup
makes it ignore the hangup signal that a dying session sends, and the
redirections (covered in Chapter 3) send its output to
/dev/null so nothing lingers on the terminal. $! expands to the PID of
the job just backgrounded, saved into sleeper.pid for later commands. An
interactive shell also prints a job-status line like [1] 8769 at this
point; the captures here show only each command's own output. Now end the
session - log out, or just close that terminal - and open a fresh one. The
sleep survived, and its parent is gone:
$ ps -o pid,ppid,stat,ni,comm -p $(cat sleeper.pid)
PID PPID STAT NI COMMAND
8769 1 S 0 sleep
The $(cat ...) substitution runs cat and inserts the recorded PID into
the command line. PPID 1 is the payoff: the shell that started the sleep no
longer exists, and systemd has adopted the orphan. Section 9.1.3 uses this
same process to look inside /proc.
9.1.2. Inspecting Processes with ps, top, and procfs
ps is a snapshot; top is a live view; /proc is the kernel's own record,
which both tools read. Which to use is mostly a question of whether you want
one answer or a moving picture.
A single process's identity is cheapest to read straight from its
/proc/<pid>/status file - grep selects the interesting lines from it:
$ grep -E "^(Name|State|Pid|PPid|Threads|VmRSS)" /proc/1/status
Name: systemd
State: S (sleeping)
Pid: 1
PPid: 0
VmRSS: 15128 kB
Threads: 1
Name is the executable's name, State spells out the STAT letter in words,
and VmRSS is the resident set - the physical memory the process actually
occupies, about 15 MiB here. The tabs in the output belong to the file
format. /proc/<pid>/ holds much more: cmdline (the command line, NUL
separated), environ (the environment), limits (Section 9.6.1), sched
(scheduling statistics), fd/ (Section 9.1.3), and wchan
(Section 9.7.2). man 5 proc documents every entry.
top summarizes the machine and refreshes a few times per second. In batch
mode it prints one frame and exits, which is how the capture was taken:
$ top -b -n 1 | head -n 12
top - 19:41:56 up 21 min, 1 user, load average: 0.25, 0.44, 0.36
Tasks: 104 total, 1 running, 103 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 1469.6 total, 1231.0 free, 222.6 used, 150.9 buff/cache
MiB Swap: 0.0 total, 0.0 free, 0.0 used. 1247.0 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1 root 20 0 24036 15128 10740 S 0.0 1.0 0:09.56 systemd
2 root 20 0 0 0 0 S 0.0 0.0 0:00.02 kthreadd
3 root 20 0 0 0 0 S 0.0 0.0 0:00.00 pool_wo+
4 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 kworker+
5 root 0 -20 0 0 0 I 0.0 0.0 0:00.00 kworker+
Read the header in order. The load average triplet is the exponential
moving average of runnable plus uninterruptible tasks over 1, 5, and 15
minutes - on this two-CPU machine, 0.25 means most capacity is idle
(Section 9.7.1 interprets it under stress). The %Cpu(s) line splits CPU
time into us (user), sy (system), ni (nice), id (idle), and wa
(iowait: the CPU idle while a task waited for disk - a high sustained wa
points at storage, not at a busy CPU). The memory lines summarize
/proc/meminfo: 1469.6 MiB total, 150.9 MiB in buffers and cache, and an
available estimate of 1247.0 MiB - the figure that matters, because it
counts reclaimable cache (Section 9.5.1). This system has no swap yet,
which Section 9.5.2 fixes. The process table adds %CPU (share of one CPU
since the last refresh), VIRT/RES/SHR (virtual, resident, and shared
memory), and PR/NI (scheduling priority and nice value).
Interactively, top runs until you quit it with q:
| Key | Effect |
|---|---|
P / M |
Sort by CPU / memory use. |
1 |
Toggle per-CPU lines in the header. |
k |
Kill a process; top asks for its PID and the signal. |
q |
Quit. |
Two habits make top more useful on a busy system: start it as
top -o %CPU (or press P) so the busiest task is on the first line, and
use top -p PID1,PID2 to watch only the processes you are arguing about.
9.1.3. Open Files, Working Directories, and File Descriptors
Each process owns a small table of file descriptors: numbered handles to
files, terminals, sockets, and pipes. Descriptor 0 is standard input, 1
standard output, 2 standard error - the three streams from
Chapter 3. The table is duplicated at fork, which is
why children inherit their parent's open files, and the kernel exposes it as
a directory of symlinks: /proc/<pid>/fd. Look at the adopted sleep from
Section 9.1.1:
$ ls -l /proc/$(cat sleeper.pid)/fd
total 0
lr-x------ 1 john john 64 Nov 19 19:42 0 -> /dev/null
l-wx------ 1 john john 64 Nov 19 19:42 1 -> /dev/null
l-wx------ 1 john john 64 Nov 19 19:42 2 -> /dev/null
The permissions (r-x or -wx) are the descriptor's mode: 0 is
read-only because it was redirected from /dev/null for input, 1 and 2
write-only. This sleep has exactly the three standard descriptors, all sent
to /dev/null by its redirections.
Anything the shell has open when it forks is inherited. Open a third descriptor in the shell, then background a new sleep:
$ exec 3>fd-demo.log
$ nohup sleep 120 >/dev/null 2>&1 &
$ echo $! > fd.pid
$ ls -l /proc/$(cat fd.pid)/fd
total 0
lr-x------ 1 john john 64 Nov 19 19:42 0 -> /dev/null
l-wx------ 1 john john 64 Nov 19 19:42 1 -> /dev/null
l-wx------ 1 john john 64 Nov 19 19:42 2 -> /dev/null
l-wx------ 1 john john 64 Nov 19 19:42 3 -> /home/john/debian-handbook/processes/fd-demo.log
exec 3>fd-demo.log opens fd-demo.log for writing as descriptor 3 of the
shell itself (the exec builtin without a command changes only the shell's
own descriptors). The background sleep inherited it: descriptor 3 appears in
the child pointing at the workspace file. Note that the sleep process did
not open that file - the shell did, and the fork copied the handle. When the
last process holding a descriptor exits, the file closes; a file is only
truly deleted when nothing holds it open. Close the exercise by stopping the
sleep, which also releases descriptor 3 everywhere:
$ kill $(cat fd.pid)
The command prints nothing; kill's default SIGTERM ends the sleep
(Section 9.2.1 explains the choice of signal).
/proc/<pid>/ also carries three symlinks that describe the process's view
of the filesystem: cwd (its working directory), exe (the program it is
executing), and root (its root directory, relevant for chroots and
containers). Reading another session's process requires root, so use the
root shell - enter it from john's shell with sudo -i and leave it later
with exit:
# ls -l /proc/8769/cwd /proc/8769/exe /proc/8769/root
lrwxrwxrwx 1 john john 0 Nov 19 19:42 /proc/8769/cwd -> /home/john/debian-handbook/processes
lrwxrwxrwx 1 john john 0 Nov 19 19:42 /proc/8769/exe -> /usr/bin/sleep
lrwxrwxrwx 1 john john 0 Nov 19 19:42 /proc/8769/root -> /
The sleep's working directory is the workspace it was started in, its
program is /usr/bin/sleep, and its root is the normal system root. These
links have practical weight: a process's cwd keeps its directory busy, so
a filesystem with a live process sitting in it cannot be unmounted cleanly
(Chapter 11 shows that failure mode), and a deleted
but running executable shows in exe as (deleted) - the classic sign of
an updated program still running from its old file.