Part 3 of 8 · 3 min read
Processes
Think of the register in a hospital. Each patient has a number, and the register holds details of each one: name, ward and status. The kernel keeps such a record for each process, and /proc shows it. The analogy stops in one place: a register is written by clerks, and /proc files are generated on demand from live kernel data.
In plain words: Every running program is a process (page 1), and every process has a number, its process ID (PID). The command ps lists processes. On the test machine:
$ ps -eo pid,ppid,comm | head -4
PID PPID COMMAND
1 0 process_api
2 0 kthreadd
3 2 pool_workqueue_release
The columns are the PID, the PID of the parent (the process that started it), and the command name. Process 1 is the first process (page 4), and its parent is 0, which stands for "the kernel itself". Process 2, kthreadd, starts kernel threads, which are tasks that run inside the kernel. Process 3 was started by process 2, so its parent is 2. Following the parent numbers upward always leads to process 1 or 2, and that gives the family tree of the system.
The key lines.
For each process the kernel provides a directory /proc/PID. The file status inside it shows many fields: the name, the state, the parent, the number of threads, the memory in use and more. A small program can read its own entry through the shortcut /proc/self:
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *f = fopen("/proc/self/status", "r");
if (!f) { perror("status"); return 1; }
char line[256];
while (fgets(line, sizeof line, f)) {
if (!strncmp(line, "Name:", 5) || !strncmp(line, "Pid:", 4) ||
!strncmp(line, "PPid:", 5) || !strncmp(line, "Threads:", 8) ||
!strncmp(line, "VmRSS:", 6))
fputs(line, stdout);
}
fclose(f);
return 0;
}
Output:
Name: e1
Pid: 584
PPid: 577
VmRSS: 1408 kB
Threads: 1
VmRSS is the resident set size: the part of the process's memory that is in physical memory right now, here 1,408 kB. The parent, 577, is the shell that launched the program. The PID changes on each run, since the kernel hands out numbers one after another.
Process ID
A process ID (PID) is the unique positive integer the kernel assigns to a process when it is created. It identifies that process in system calls and commands for as long as the process exists, and the number can be reused after the process has ended and been collected.
Example: ps shows the PID of every process, and /proc/584 is the directory with the details of process 584.
Check yourself: 1. What does a PPID of 0 mean? 2. Which directory describes the process with PID 584? 3. Why does the same program show a different PID on each run?