5/32 · 5 min
What a process actually is
A program is a file on disk. A process is that file being run: the code, plus everything the operating system has to remember about it.
What the kernel keeps
Every process has a process control block, which is a struct in kernel memory holding:
- Its identifier, the PID.
- Its state: new, ready, running, waiting, terminated.
- The saved registers, including the program counter, so it can be resumed exactly where it stopped.
- Its memory mappings.
- Its open files.
- Its parent, and accounting like CPU time used.
Switching from one process to another means saving all of that for one and loading it for another. That is a context switch, and it is not free.
The five states
new -> ready <-> running -> terminated
^ |
| v
+---- waitingReady means it could run and is queueing for a processor. Waiting means it could not run even if a processor were free, because it is blocked on something: a disk read, a keyboard press, a network reply.
The difference matters enormously. A hundred ready processes means the machine is busy. A hundred waiting processes means the machine is idle and something else is the bottleneck.
fork
On Unix a process is created by copying an existing one:
pid_t pid = fork();
if (pid == 0) {
// the child, a near-identical copy
} else {
// the parent, with the child's PID
}fork returns twice: zero in the child, the child's PID in the parent. Both carry on from the same line.