Operating Systems · Lecture Notes

Chapter 3: Processes

A computer typically runs a browser, a music player, a compiler, and dozens of background services all at once. The operating system sees each of them as a separate process. Every process has its own memory, its own register values, and its own open files. The process is the basic unit of the operating system’s division of labor: the processor is handed out to processes, memory is allocated to processes, and files are opened on behalf of processes. These notes begin with the question of what a process is and how it is laid out in memory. They then use code traces to show how the UNIX calls fork, exec, wait, and exit create and end processes. Process states, the process control block, queues, and context switching show how the kernel keeps track of processes. The last sections cover how processes communicate with each other and why mobile systems restrict background processes.

Learning outcomes

Process model
Explain the difference between a program and a process and describe the memory layout of a process; say in which region each variable of a C program lives.
Life cycle
Define the process states and the transitions between them; explain the contents and purpose of the process control block (PCB).
UNIX API
Trace small programs that use fork(), exec(), wait(), exit(), and pipe() line by line; determine their output and the number of processes they create.
Scheduling infrastructure
Explain and compute with the ready and wait queues, the effect of multiprogramming on CPU utilization, and the cost of a context switch.
IPC
Compare shared memory, message passing, pipes, and sockets in terms of speed, coordination, and typical use.
Mobile multitasking
Explain why and how iOS and Android restrict background processes.

3.1The process concept

The operating system hides the difficulty of using hardware directly behind a few abstractions. A file is an abstraction of disk blocks; an address space is an abstraction of physical memory. The process is the abstraction of the processor. Thanks to the process concept, even a single processor can be used as if every program had a processor of its own. This section defines the process, shows how it looks in memory, and explains how many processes make progress at the same time.

3.1.1Program and process

A file such as a.out or vim sitting on disk is a program. A program is an executable file made up of machine instructions and initial data. By itself it does nothing; it waits on disk. A program is therefore a passive entity.

When a program is run, the operating system allocates memory for it, loads its instructions into memory, and tells the processor “start here.” From that moment on, there is a running activity. It has a program counter (the address of the next instruction), register values, a stack, open files, and an identification number. This live entity is called a process.

Definition 3.1

A process is an instance of a program in execution. A process has three components: an address space holding the program’s code and data, the current state of the processor (the program counter and registers), and resources. Resources are the open files, memory regions, and identity information that the operating system allocates to the process. Every process carries a unique process identifier (PID) within the system.

The relationship between a program and a process resembles the relationship between a recipe and a dish cooking in the kitchen. The recipe sits on paper and does not change. Cooking is a process: which step you are at, what is in the pot, whether the stove is on all change from moment to moment. Two dishes can be cooked from the same recipe in two different kitchens at the same time, and neither affects the other.

The same holds for programs. When vim is opened in two terminal windows, a single file on disk gives rise to two processes. Each has its own address space, its own open files, and its own cursor position. Text typed in one does not appear in the other. The read-only code of the program, however, can be shared between the two processes; keeping two copies of the same machine instructions in memory would be wasteful. Figure 3.1 shows this situation.

a.outprogram (on disk)passive · filerunrunprocess · PID 4021textdataheapstackactive · in memory · own PCBprocess · PID 4022textdataheapstackactive · in memory · own PCBfrom the same programtwo separate processes:separate address spaces,separate state and resources
Figure 3.1: When the single program a.out on disk is run twice, two separate processes result (PIDs 4021 and 4022). Each process has its own text, data, heap, and stack regions and its own PCB.

Inside a process, instructions can run in a single sequence or in several sequences. A single-threaded process has one program counter and executes its instructions one after another. A multithreaded process has several program counters. Its threads share the same address space and, on a multicore machine, can truly make progress at the same time. Unless stated otherwise, the processes in these notes are single-threaded.

Common mistake

Using the words “program” and “process” interchangeably. A program is a file and consumes no resources by itself. A process consumes memory, processor time, and open files. A program may never run, may run once, or may run a hundred times at once; each run is a separate process.

3.1.2Process layout in memory

Every process sees memory as if it were one contiguous array of its own. The addresses of this array make up the address space. Extending from 0 up to the highest address, this space is divided into several regions. Each region has its own purpose and its own access rights. Figure 3.2 shows the regions from bottom to top.

kernel spacemapped into every process; not accessible in user modestacklocal variables, parameters, return addressesfree spaceheapmemory allocated at run time with malloc() / newBSSuninitialized globals / statics (zeroed)datainitialized global / static variablestextthe program’s machine code (read-only, shareable)growsgrowshigh addressnear address 0
Figure 3.2: The memory layout of a process. At low addresses, the text, data, and BSS regions have fixed sizes. The heap grows upward and the stack grows downward; the free space between them leaves room for both to grow. The kernel space at the top is mapped into every process but is not accessible in user mode.

Let us take the regions one by one, starting from the lowest address:

  • The text region holds the program’s compiled machine code. It is read-only: a process cannot accidentally modify its own code. Processes created from the same program can share this region.
  • The data region holds initialized global and static variables. These values are stored inside the executable file and copied into memory at load time.
  • The BSS region holds uninitialized global and static variables. The name comes from an old assembler directive (block started by symbol). All of these variables start at zero. The file records only the size of the region; the loader allocates that much zeroed memory. A 4 MB array of zeros therefore does not make the executable 4 MB larger.
  • The heap satisfies memory requested at run time with malloc() (or new in C++ and Java). As the program asks for memory, the heap grows upward; space released with free() is reused.
  • The stack tracks function calls. Each call pushes a frame onto the stack: the parameters, local variables, and return address live in this frame. When the function returns, the frame is popped. The stack grows downward from high addresses.
  • The kernel space is the topmost part of the address space. The kernel’s code and data are mapped here, so the address space need not be switched during a system call. Code running in user mode cannot touch this region; if it tries, the hardware raises a fault.

That the heap and the stack grow toward each other is a deliberate design. It is not known in advance how much each region will grow: a recursive program uses a lot of stack, while a program that processes large data uses a lot of heap. Because they share the free space between them, memory can be divided flexibly between the two.

The program counter does not appear in this picture because it is a register inside the processor, not something in memory. The program counter points to an address in the text region: it is the process’s “current position.” The stack pointer, which points to the top of the stack, is also a register. When the process leaves the processor, the kernel saves these registers somewhere so that their values are not lost. That place is the process control block, discussed in 3.4.4.

In real systems the addresses of the regions are not the same on every run. Address space layout randomization (ASLR) shifts the starting addresses of the stack, the heap, and the shared libraries randomly on each run. Because an attacker cannot predict what is where in memory, many attacks become harder. The order of the regions and their directions of growth do not change.

3.1.3Where do variables live?

The best way to make the regions concrete is to find where each name in a small C program lands. The program below is the same as the one in the slides:

#include <stdlib.h>
int counter = 5;    /* data */
int table[1000];  /* bss */

int main(int argc, char *argv[]) {
    int local = 3;
    static int count;
    int *p = malloc(4 * sizeof *p);
    p[0] = local + counter;
    free(p);
    return 0;
}

Let us find where each element of the program lives, one by one. Figure 3.3 shows the four regions other than text side by side.

Example 3.1
  1. Text. The compiled instructions of the main function are in the text region. The code of malloc and free also sits in the text region of the C library. This region is read-only and can be shared among processes of the same program.
  2. Data. int counter = 5; is global and initialized. The value 5 is stored in the executable file and copied into the data region at load time.
  3. BSS. int table[1000]; is global but uninitialized; its 4000 bytes start at zero and take no space in the file. The static int count; inside main is in BSS as well. Being declared inside a function does not put it on the stack; the keyword static makes the variable live for the whole program run.
  4. Stack. When main is called, a frame is opened on the stack. argc, argv, the local variable local = 3, the pointer p itself, and the return address are in this frame. When main returns, the frame disappears.
  5. Heap. malloc(4 * sizeof *p) allocates 4 · 4 = 16 bytes from the heap (assuming a 4-byte int). p is on the stack, but the 16 bytes it points to are on the heap. The line p[0] = local + counter writes 3 + 5 = 8 into the first cell on the heap. free(p) returns this space; the variable p itself stays on the stack.
kernel spacestack↓ free ↑heapBSSdatatextcounter = 5 kernel spacestack↓ free ↑heapBSSdatatexttable[1000]count (static)
kernel spacestack↓ free ↑heapBSSdatatextargc, argvlocal = 3p (the pointer itself)return address kernel spacestack↓ free ↑heapBSSdatatext*p → 16 bytes(via malloc)
Figure 3.3: Where the names in the example program live. (a) Data: counter = 5. (b) BSS: table[1000] and static count. (c) Stack: the frame of main; argc, argv, local, p, and the return address. (d) Heap: the 16 bytes allocated by malloc.

On Linux this layout can also be seen from the command line. The command size a.out prints the sizes of the text, data, and BSS regions. All regions of a running process are listed by cat /proc/PID/maps. In that listing you see lines named [heap] and [stack] along with the ranges where the program and its libraries are mapped.

Common mistake

Saying “the pointer lives on the heap.” In the line int *p = malloc(16); there are two separate pieces of memory. The variable p is local, so it is on the stack and holds an 8-byte address. The 16 bytes that this address points to are on the heap. When the function returns, p disappears, but if free was not called, the space on the heap remains allocated. This is exactly what a memory leak is.

3.1.4Pseudoparallelism and multiprogramming

A single-core processor can execute only one instruction stream at any instant. Even so, a user can listen to music and write a document at the same time. This is possible because the processor switches among processes very quickly. Each process runs for a few milliseconds, and then the processor moves on to the next. Because there are hundreds of switches per second, the user believes that all the processes run at once. This illusion is called pseudoparallelism.

Definition 3.2

Multiprogramming is keeping several processes in memory at the same time and sharing the processor among them. The goal is not to leave the processor idle while a process waits (for example, for data to arrive from disk) but to keep it busy with another process. The scheduler decides which process gets the processor.

Figure 3.4 shows this situation from three viewpoints. Part (a) shows the physical reality: a single program counter moves in turn among processes A, B, C, and D. Part (b) is the conceptual model: each process is thought of as an independent activity with its own logical program counter. When a process leaves the processor, the value of the physical program counter is saved into that process’s logical counter. Part (c) is the time axis: over a long interval all four processes have made progress, but at any instant only one of them runs.

(a) one program counterABCDprocessswitch(b) four independent processesABCDeach has its own logical PC(c) only one runs at a timetimeDCBA
Figure 3.4: Multiprogramming. (a) A single program counter switches among four processes. (b) Conceptually there are four independent processes, each with its own logical program counter. (c) On the time axis every process makes progress, but only one runs at any instant.

The length that determines how often switches occur is called the time slice (or quantum). Typical values are a few milliseconds. In EEVDF (Earliest Eligible Virtual Deadline First), the scheduler of current Linux kernels, the base slice is about 3 ms. In the older Completely Fair Scheduler (CFS), the target time for every ready process to run once was between 6 and 24 ms, depending on the number of cores.

Pseudoparallelism is convenient for the user but carries a warning for the programmer: it cannot be known in advance when a process will be interrupted. An interruption can occur in the middle of an instruction sequence, between two lines, even between the read and the write of a variable. The speed of a process is not constant either; the same loop may take 2 ms in one run and 20 ms in another. A correct program therefore makes no assumptions about timing. Thoughts such as “the child process has surely finished by now” or “these two lines run without interruption” can be guaranteed only by an explicit coordination mechanism.

3.1.5Concurrency and parallelism

Two words that are used interchangeably in everyday language describe different things in operating systems.

Definition 3.3

Concurrency is the progress of several tasks in the same time interval. Tasks can run interleaved on a single core; at any instant only one may be running. Parallelism is the physical execution of several tasks at the same time and requires several cores or processors.

Figure 3.5 shows the difference clearly. In the top row, a single core runs tasks A, B, and C piece by piece in turn: all three tasks progress in the same interval, but at no moment do two run together. The lower part has two cores; A and C run at the same time. A parallel system is always concurrent, but a concurrent system need not be parallel.

Concurrency(1 core)ABCABCABParallelism(2 cores)AAABBBAACCCCAACCcore 0core 1time
Figure 3.5: Concurrency on one core and parallelism on two cores. At the top the tasks interleave; at the bottom two cores run different tasks at the same time.

Multicore processors are now everywhere; as of 2026 even phones have 6 to 10 cores. This does not mean that switching is no longer needed. Even an ordinary laptop has hundreds of processes, and the number of cores is far below that. Multiprogramming and switching between processes therefore live on in every system, whatever the number of cores.

3.1.6Example: Chrome’s multiprocess architecture

One of the examples that best shows the practical value of the process concept is the Chrome browser. Older browsers ran as a single process. A faulty page or plugin in one tab could crash the entire browser. Chrome instead splits the work among many processes (Figure 3.6).

Browser processUI, tabs, permissions, diskRenderersite ARenderersite BGPU processdrawingNetwork serviceHTTP, cachePlugin / helperextension, audio...IPC (Mojo)renderers run in a sandbox;if one tab crashes, the browser and other tabs survive
Figure 3.6: Chrome’s multiprocess architecture. The privileged browser process, the sandboxed renderer processes, and the GPU, network, and helper processes communicate through an IPC system called Mojo.
  • The browser process is unique and privileged. It manages the user interface, the tabs, disk access, and permissions.
  • The renderer processes handle HTML, CSS, and JavaScript. Thanks to site isolation, each site runs in a separate renderer process. These processes run in a sandbox: they cannot access the disk or the network directly and pass every request on to the browser process.
  • The GPU, network, and helper processes run drawing, network traffic, and extensions in separate processes. Legacy plugin support has been removed: NPAPI plugins in 2015, Flash at the end of 2020.

This design has three benefits. The first is stability: if a tab crashes, only its renderer process dies, and the browser and the other tabs keep working. The second is security: even if a malicious page takes over its own renderer process, it cannot escape the sandbox or read the data of other sites. The third is parallelism: different tabs can run in parallel on different cores. The price is memory; every process carries its own address space and data structures. A Chrome with many tabs therefore uses more memory than a single-process browser.

3.2Process creation

Every process in the system is born from another process. This section describes the events and system calls through which processes are created. The emphasis is on the two basic UNIX calls: fork(), which makes a copy of the process, and exec(), which replaces the program in the process. Used together, they also explain how the shell runs a command and how it redirects output to a file.

3.2.1Events and system calls that create processes

A new process comes into existence through four kinds of events:

  1. System boot. After the kernel is loaded, it starts the first user process. On Linux this is usually systemd, which in turn starts the services that run continuously in the background. These services, which do not interact directly with the user, are called daemons; the web server, the print service, and the logger are of this kind.
  2. A request from a running process. A process can create new processes to divide its work. For example, a build tool starts a separate compiler process for each source file.
  3. A user starting a command or an application. Typing ls in the shell or clicking an icon on the desktop creates a new process.
  4. Starting a batch job. On large servers and compute clusters, queued jobs are started as processes when resources become free.

These four cases look different from the outside, but technically the same thing happens: an existing process makes a system call that creates a new process. Even at boot, the kernel itself prepares the first process; every later process is born from a call by an earlier one.

Table 3.1: System calls that create processes.
SystemCall
UNIX / Linuxfork() + exec(); also posix_spawn(), and clone() on Linux
WindowsCreateProcess(): creates the process and loads the program in a single call

UNIX splits the job into two steps. fork() creates a copy of the calling process; exec() replaces the program inside a process with another program. Windows’ CreateProcess() does both at once: it creates the new process and loads the given program into it. posix_spawn() offers a one-step route on UNIX as well. Linux’s clone() call lets the caller choose individually what the new task shares with its parent (memory, files, signal handlers); threads are created with this call too.

The process that creates a process is called the parent, and the created process is called the child. A child can create children of its own. Every process carries a unique PID and knows the PID of its parent.

3.2.2The process tree

Parent–child relationships form a tree. On Linux, the root of the tree is systemd (or another init program), which starts at boot with PID 1. kthreadd, with PID 2, is the parent of the kernel threads; in-kernel workers such as kworker sit under it. Figure 3.7 shows a slice of the tree of a typical desktop system. The PID values in the figure are examples; real values change on every boot.

systemdPID 1kthreaddPID 2journaldPID 312sshdPID 890gdmPID 1003kworker/0:1PID 57sshd (session)PID 2101gnome-shellPID 1520bashPID 2105firefoxPID 2310vimPID 2230psPID 2241kernelthreads$ pstree -p$ ps -ef --forest
Figure 3.7: A slice of the Linux process tree. systemd (PID 1) is the root of the user processes and kthreadd (PID 2) is the root of the kernel threads. The tree can be seen with pstree -p or ps -ef --forest.

The trace of a shell session is easy to read in the tree. When a user connects over SSH, sshd (PID 890) creates a new sshd (PID 2101) for the session. That one starts the user’s shell (bash, PID 2105). Every command typed in the shell, such as vim or ps, becomes a child of the shell. In the ps output, each process is listed with its parent’s PID (PPID); this column gives the branches of the tree.

3.2.3The parent–child relationship

When a new process is created, the operating system answers four questions:

  • Resource sharing: The child may share all, some, or none of the parent’s resources. In UNIX, the child inherits the parent’s open file descriptors; it reaches the same files under the same numbers.
  • Execution: The parent and child can run concurrently. Alternatively, the parent can wait for the child to finish with wait().
  • Address space: In UNIX, after fork() the child gets a copy of the parent’s address space. They do not share the same memory. The child can then load a new program into itself with exec().
  • Identifiers: getpid() returns the process’s own PID, and getppid() returns the PID of its parent.

Copying the address space looks expensive: if the parent has hundreds of megabytes of memory, is all of it copied? No. The child’s address space is logically separate from the parent’s, but the physical pages are shared until one of them writes. This technique is called copy-on-write and is the subject of a later subsection.

3.2.4fork(): one call, two returns

fork() is unlike ordinary functions: it is called once but returns twice, once in the parent and once in the newly created child. Both processes continue from the line right after the call. The only way to tell which is which is the return value.

Definition 3.4

pid_t fork(void) creates a new process that is a copy of the calling process. On success it returns the child’s PID (a positive number) to the parent and 0 to the child. On failure no child is created and −1 is returned to the parent only; the reason is stored in the variable errno.

These three cases determine the pattern written after every fork:

pid_t pid = fork();
if (pid < 0)        { perror("fork"); exit(1); }
else if (pid == 0)  { /* child: fork returned 0 */ }
else                { /* parent: pid = child's PID */ }

Why does the child get 0 instead of its own PID? Because the child can always learn its own PID with getpid() and its parent’s with getppid(). The parent, however, has no other way to learn the child’s PID. A parent may have many children and needs their PIDs to wait for them or to send them signals. The value 0 is also a safe marker because no user process can have PID 0.

In the kernel, fork does the following: it allocates a new PCB and copies the parent’s into it; assigns the new PID; copies the open file table; and copies the page table. It does not copy the pages themselves. Figure 3.8 shows how this works in three stages.

parent (PID 1234)page tablephysical memory (frames)page Apage Bpage C
parent (PID 1234)page tablechild (PID 1235)page tablephysical memory (frames)page Apage Bpage Cwrite-protectedshared mapping(read-only)
parent (PID 1234)page tablechild (PID 1235)page tablephysical memory (frames)page Apage Bpage Cpage C′copywrite-protectedshared mapping(read-only)child wrote to C →page fault →kernel copied the page
Figure 3.8: fork() and copy-on-write. (a) The parent’s page table points to physical pages A, B, and C. (b) After fork, the child’s page table points to the same pages; the pages are mapped read-only on both sides. (c) When the child writes to C, a page fault occurs; the kernel copies only that page (C′) and redirects the child’s table to the new copy.
Definition 3.5

Copy-on-write (COW) means that two processes share the same physical page read-only, and the page is copied only when one of the processes tries to write to it. The write attempt raises a page fault; the kernel copies the page, points the writing process’s page table at the new copy, and enables write permission.

Thanks to copy-on-write, the cost of fork is proportional to the size of the page table, not to the size of the address space. More importantly, if the child is going to call exec right away (which is almost always the case in a shell), almost no pages are copied. The pages that would be copied are discarded during exec anyway. The details of COW belong to virtual memory; here only its consequence matters: logically, the child is a complete copy of the parent, and neither side can change the other’s variables.

Common mistake

Assuming that the parent and child share variables after fork. A global variable, an array on the heap, or a local variable on the stack becomes two separate copies at the moment of fork. An assignment made by the child does not affect the parent’s copy. For processes to share data, you must explicitly set up shared memory, a pipe, or another IPC mechanism.

3.2.5Code trace: fork() and wait()

The following program shows that after fork the two processes work with separate variables, and how wait fixes the order of the output:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    int x = 10;
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); exit(1); }
    if (pid == 0) {
        x = x + 5;
        printf("child: x=%d\n", x);
        return 0;
    }
    wait(NULL);
    printf("parent: x=%d\n", x);
    return 0;
}

The program starts with x = 10 on line 7 and calls fork on line 8. If fork fails, it returns −1; in that case line 9 prints the error and ends the program. After that there are two processes, each with its own x. In the child, pid == 0, so the if block is entered; the parent skips both ifs and reaches wait(NULL). wait blocks the calling process until one of its children finishes and returns the PID of the finished child. The NULL argument says that the child’s exit status is of no interest. Let the parent’s PID be 1234 and the child’s 1235. Table 3.2 gives the steps of one run.

Table 3.2: Trace of the fork() + wait() program (parent 1234, child 1235).
StepLineParent (1234)Child (1235)Output
17running; x = 10—
28pid = 1235, x = 10created; pid = 0, x = 10
315wait(NULL) → waitingready
410waitingrunning; pid == 0 is true
511waiting; x = 10x = 15
612waitingprintfchild: x=15
713woken up (SIGCHLD)return 0 → zombie
815wait returns 1235reaped (entry deleted)
916printf; x is still 10—parent: x=10
1017terminated—

Three points of the trace are important. First, in step 5 the child sets x to 15, but the parent’s x stays at 10. There are two separate variables with the same name; in step 9 the parent prints 10. Second, the order of steps 3 and 4 in the table can vary. After fork, the child may run first; then the child prints and exits, and when the parent reaches wait the child has already finished, so wait returns immediately. In either order the output is the same:

child: x=15
parent: x=10

Third, in step 7, when the child returns from main, it does not vanish at once. The C runtime calls exit(0) with the return value of main. The kernel reclaims the child’s memory but keeps its exit status until the parent reads it. During this short interval the child is a zombie. The kernel sends the parent a SIGCHLD signal and wakes it up. In step 8, wait collects the child’s status and deletes its entry from the process table. This operation is called reaping. Zombies and reaping are treated in detail in 3.3.4.

3.2.6Without wait(), the output order is undefined

What happens if wait is removed from the previous program? Consider the following short fragment:

pid_t pid = fork();
if (pid == 0) printf("child\n");
else          printf("parent\n");

After fork, both processes are ready, and the scheduler decides which runs first. The program has no way to influence this decision. Figure 3.9 shows two possible schedules on a single core: in one the parent prints first, in the other the child. On a multicore machine the two processes can even run at the same time. On Linux, which one runs first has varied with the version and the configuration; the programmer cannot rely on it.

Schedule 1fork()parent: printfchild: printfparentchildSchedule 2fork()child: printfparent: printfchildparenttime (single core)
Figure 3.9: Two different schedules and two different output orders after fork. At the top the parent runs first, at the bottom the child; the terminal boxes show the output seen on screen.

If the correctness of the program depends on this order (for example, if the parent is going to read a file written by the child), the order must be established explicitly. The simplest way is wait() or waitpid(). For more complex cases there are pipes, semaphores, and other coordination tools. That the output order changes from run to run is the first sign of the most fundamental problem in concurrent programs: the result must not depend on timing that cannot be controlled.

3.2.7How many processes are created? Buffered output and fork()

The behavior of fork that doubles the number of processes at every call is a staple of exam questions. Getting the rule right once makes even the most tangled-looking question easy. The rule is this: if k processes reach a fork line at that moment, there are 2k processes after the line. Each one produces a child, and the child continues from the same line.

fork();
fork();
printf("X\n");          /* how many times? */

for (int i = 0; i < 3; i++)
    fork();
printf("Y\n");          /* and this one? */
Example 3.2
  1. First fragment. At the start there is a single process. After the first fork there are 2. Both run the second fork; then there are 4. All four reach printf: 4 lines of X are printed. The number of newly created processes is 3.
  2. Fragment with a loop. The loop runs three times, for i = 0, 1, 2. In each round the number of processes doubles: 1 → 2 → 4 → 8. The children also carry a copy of the loop variable and continue the loop from where they were. In the end 23 = 8 processes print Y; 7 of them are new.
  3. Generalization. If n unconditional forks run one after another, 2n processes result and 2n − 1 of them are new. With conditional forks (for example if (fork() && fork())) this rule cannot be applied directly; the return value must be followed separately for each process.

Finding the number of processes is not enough; sometimes the content of the output is surprising as well. Consider these three lines:

printf("A");
fork();
printf("B\n");

The answer that comes to mind is “one A and two Bs.” Yet the program prints two lines of AB. The reason is the C library’s output buffer. printf does not send characters to the kernel immediately; it first writes them into a buffer in the process’s own memory. The buffer is flushed only in certain situations, and its contents go to the kernel with the write system call. When writing to a terminal, the buffer is line-buffered: it is flushed when a newline (\n) arrives. When writing to a file or a pipe, it is fully buffered: it is flushed when it fills up or when the process exits.

The "A" in the first line contains no newline, so it is still in the buffer at the time of fork. Because the buffer lives in the process’s memory, fork copies it too. Now both processes have A in their buffers. Each process appends "B\n" and prints AB with the newline. Whether the output goes to the terminal or is redirected to a file, AB appears twice.

If the first line were printf("A\n"), the result would depend on where the output goes. On a terminal, line buffering flushes A before the fork, and the output is A, B, B. If the output is redirected to a file with ./prog > output.txt, full buffering keeps holding A\n. In that case both processes print A, B at exit; the file contains four lines: A, B, A, B.

Common mistake

Assuming that the text has been written to the screen or the file by the time printf returns. If the buffer is not flushed before fork or exec, unwritten data is either duplicated or lost. The safe way is to call fflush(stdout) before fork. For error messages, stderr is preferred because stderr is unbuffered.

3.2.8The exec() family

fork produces only a copy; if the shell did nothing but copy itself on every command, it could never run ls. A second call is needed to run another program. The functions in the exec family replace the program inside the calling process with another program from disk.

Definition 3.6

The exec family replaces the calling process’s memory image (code, data, heap, and stack) with a new image loaded from the given executable file. No new process is created: the PID, the parent relationship, and the open file descriptors that were not closed are preserved. A successful exec does not return to the calling code; if it does return, an error has occurred and the return value is −1.

before execafter execlp("ls", ...)PID 1235 · PPID 1234text: a.out codedata / BSSheapstackopen files 0,1,2cwd, identitiesPID 1235 · PPID 1234text: ls codenew data / BSSnew (empty) heapnew stack: argvopen files 0,1,2cwd, identitiesthe address space iscompletely reloadedpreserved: PID, PPID,open file descriptors
Figure 3.10: exec replaces the process image. On the left, the code and data of a.out go away; in their place come the code of ls, new data, an empty heap, and a new stack carrying argv. The PID, PPID, open files, working directory, and identities are preserved.

The six members of the family do the same job; they differ only in how the arguments are passed. The letters in their names encode the difference. l (list): the arguments are given one by one, as a list ending with NULL. v (vector): the arguments are given as an array. p (path): the program is searched for in the directories of the PATH environment variable. e (environment): the environment variables are given explicitly.

Table 3.3: The exec family.
CallArgumentsPATH searchEnvironment
execl / execvlist / arraynoinherited
execlp / execvplist / arrayyesinherited
execle / execvelist / arraynogiven explicitly

All of these functions are defined in the C library and end up in a single system call: execve(). For example, execlp("ls", "ls", "-l", NULL) first searches for ls in PATH and finds /usr/bin/ls. It then turns the arguments into the array {"ls", "-l", NULL} and calls execve. Repeating the program’s name in the first argument is a convention: this value becomes argv[0] in the new program.

Common mistake

Forgetting to end the argument list with NULL or leaving out argv[0]. In the call execlp("ls", "-l", NULL), -l is taken as the program’s name (argv[0]) and ls runs without any options. If the NULL is forgotten, the library cannot find the end of the list and takes random values in memory for arguments.

3.2.9What does exec do in the kernel?

From the outside, exec is a single step: the process is one program and then becomes another. Inside the kernel, six steps are carried out in order.

  1. Open the file; check permission and format. If the file does not exist, lacks execute permission, or has an unrecognized format, exec returns −1 and the old program continues where it left off. Linux recognizes two formats: binaries that begin with an ELF header and scripts that begin with a #! line. For a script, the kernel runs the interpreter named after #! (for example /bin/sh) and passes the script’s name to it as an argument.
  2. Discard the old address space. The code, data, heap, and stack mappings are deleted; any other threads in the process are terminated. From this point on there is no program to return to. That is why all the checks are done in the first step.
  3. Close descriptors marked close-on-exec; reset signal handlers. Files opened with O_CLOEXEC are closed; the others stay open. Caught signals revert to their default action, because the code of the handler function is no longer in memory. Ignored signals remain ignored.
  4. Map the code and data segments from the file. Nothing is copied. When a page is used for the first time, a page fault occurs and that page is brought in from disk. Thanks to this lazy loading, the parts of a large program that are never used never come into memory.
  5. Allocate zeroed memory for BSS, heap, and stack. At the top of the stack the kernel places the argv and envp strings, the arrays of pointers to them, and argc.
  6. Set the program counter to the entry point; return to user mode. The entry point is not main but the C runtime’s _start routine. _start sets up the runtime and calls main(argc, argv, envp). When main returns, it calls exit with the return value. Throughout this whole operation the PID never changes.
old code, data, heap,stack: discardedpreserved:PID and parentopen fds (except cloexec)working directory, usersignal maskprog (ELF)header.text.datastackargc, argv, envpemptyheap (empty)bss (zeroed)datatext (code)PC = entry (_start)mapping is lazy: a page is read on first access
Figure 3.11: The new address space after exec. Text and data are mapped lazily from the file; BSS, heap, and stack come from zeroed memory; argc, argv, and envp sit at the top of the stack. The old code, data, heap, and stack are gone; the PID, parent, open descriptors (except close-on-exec ones), working directory, and user ID are preserved.

An important consequence follows from this order: the line after exec runs only if exec fails. There is therefore no need to write an if (… == -1) check after exec; if the following line is reached, there is already an error. The right pattern is to print the error and terminate the process right after exec.

3.2.10Code trace: fork, exec, and waitpid

The following program is the complete pattern for running another program on UNIX: copy, replace the program in the child, wait in the parent.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
  pid_t pid = fork();
  if (pid < 0) { perror("fork"); exit(1); }
  if (pid == 0) {
    execlp("ls", "ls", "-l", NULL);
    perror("execlp");  /* error */
    exit(1);
  }
  int st;
  if (waitpid(pid, &st, 0) < 0) { perror("waitpid"); exit(1); }
  if (WIFEXITED(st)) printf("done: %d\n", WEXITSTATUS(st));
  return 0;
}

Here waitpid is used instead of wait. waitpid(pid, &st, 0) waits for a specific child and writes its exit status into st. The third argument carries options; 0 means “wait until it finishes.” st encodes not only the exit code but also how the process ended. WIFEXITED(st) tells whether it was a normal exit, WEXITSTATUS(st) gives the exit code, and WIFSIGNALED(st) tells whether it was killed by a signal. WEXITSTATUS is meaningful only if WIFEXITED is true; that is why line 16 tests it first. Lines 8 and 15 also catch the error case in which fork and waitpid return −1.

Table 3.4: Trace of fork + exec + waitpid (parent 1234, child 1235).
StepLineParent (1234)Child (1235)Output
17pid = 1235pid = 0; the same a.out image
215waitpid(1235, …) → waitingready
310waitingexeclp: ls is found in PATH; the image becomes /usr/bin/ls, the PID is still 1235
4—waitingls -l runs; writes to the stdout it inherited(output of ls -l)
515woken up; waitpid returns, st = encoded 0exit(0) → reaped
616WIFEXITED(st) is true; prints WEXITSTATUS(st) = 0—done: 0

Step 3 is the heart of the program. Because execlp succeeds, lines 11 and 12 in the child never run: the code containing those lines is no longer in memory. From then on the child process is the ls program. ls does not know who started it; it simply writes to file descriptor 1. That descriptor was inherited from the parent and points to the terminal. This is why the listing appears on the screen.

If the file name were mistyped, for example execlp("lss", …), execlp would return −1. The child would print the message execlp: No such file or directory with perror on line 11 and exit with exit(1). The parent would then print done: 1. What if the exit(1) line were forgotten? The child would leave the if block and continue at line 14, executing the parent’s code. Because pid is 0 in the child, waitpid(0, …) is called; since the child has nothing to wait for, it returns −1, and the child prints waitpid: No child processes and exits. Without error checking, the child might even print a second “done” line with a meaningless st. This is one of the most common mistakes in programs that use fork.

3.2.11The shell loop: fork, exec, wait

The command-line shell is a program that runs the pattern of the previous subsection in an infinite loop. Each round of the loop consists of six steps. Figure 3.12 shows one round.

  1. The shell (bash, PID 2105) shows the prompt and reads the command ls that the user typed.
  2. It creates a copy of itself (PID 2300) with fork(). The parent waits with waitpid(2300, …).
  3. The child calls execvp("ls", argv); its image is replaced by ls.
  4. ls runs and writes to the terminal stdout it inherited.
  5. ls exits. The kernel notifies the parent with SIGCHLD and waitpid reaps the child.
  6. The shell shows the new prompt and the loop starts over.
bashPID 2105lsPID 2300fork()execvp("ls")image is replaced by lswaitpid(2300)→ waitinglsrunswrites to stdoutexit(0) → SIGCHLDchild is reaped$ new prompt
Figure 3.12: One round of the shell loop. bash forks, the child turns into ls and writes to the terminal, SIGCHLD arrives on exit, and the shell reaps the child and shows the new prompt.

If & is added to the end of the command (sleep 60 &), the shell does not call waitpid in step 2; it shows the new prompt immediately. This is a background job. A background child must also be reaped when it finishes. The shell does this when SIGCHLD arrives, or by collecting the waiting children before the next prompt.

3.2.12Why are fork and exec separate? Output redirection

While Windows makes do with a single CreateProcess call, why does UNIX use two calls? The answer lies in the short interval between them. After fork and before exec, the child is still running the shell’s code. Meanwhile it can change its own environment as it likes: it can redirect file descriptors, change the working directory or the priority, and ignore some signals. Then it moves on to the new program with exec. The new program inherits these changes but knows nothing about them.

This is what happens when wc -l notes.txt > count.txt is typed in the shell. The following program does the same job:

int main(void) {
  pid_t pid = fork();
  if (pid == 0) {    /* child */
    close(1);        /* stdout freed */
    int fd = open("count.txt",
             O_WRONLY | O_CREAT | O_TRUNC, 0644);
    /* lowest free number: fd == 1 */
    execlp("wc", "wc", "-l", "notes.txt", NULL);
    perror("execlp");
    exit(1);
  }
  waitpid(pid, NULL, 0);
  printf("done\n");
  return 0;
}

The key to the program is that open always returns the lowest free descriptor number. The child first closes stdout with close(1); number 1 becomes free. The count.txt opened right afterward therefore receives number 1. Figure 3.13 shows how the child’s file descriptor table changes.

child’s fd table (copy of the parent’s)0 → tty1 → tty2 → ttyparent: 0, 1, 2 → terminal (unchanged) child’s fd table0 → tty1 → (free)2 → ttyparent: 0, 1, 2 → terminal (unchanged)
child’s fd table0 → tty1 → count.txt2 → ttyparent: 0, 1, 2 → terminal (unchanged) child = wc · fd table preserved0 → tty1 → count.txt2 → ttyparent: 0, 1, 2 → terminal (unchanged)
Figure 3.13: The child’s file descriptor table. (a) After fork: 0, 1, and 2 point to the terminal. (b) close(1): number 1 becomes free. (c) open returns the lowest free number, 1; stdout is now the file. (d) exec replaces the code and preserves the table: wc writes to the file without knowing it. The parent’s table is unchanged throughout.
Table 3.5: Trace of output redirection (parent 1500, child 1501).
StepLineChild’s fd 1EventScreen
12terminalfork: the child copies the parent’s fd table
212terminalthe parent waits with waitpid
34(free)the child calls close(1)
45–6count.txtopen returns 1: fd == 1
58count.txtexec: the child is now wc -l; it writes its result to fd 1
613—wc finishes; the parent writes to its own fd 1, the terminaldone

Only done appears on the screen. The output of wc (for example 42 notes.txt) has gone to count.txt; it can be seen with cat count.txt. There is not a single line about redirection in the source code of wc. The program simply writes to number 1; what that number points to was set by the shell before exec.

This program assumes that no other file is opened between close and open. Real shells do the same job more safely with dup2(fd, 1): they open the file under any number and then redirect number 1 to it. Windows’ CreateProcess asks for the same settings (standard input and output, working directory, priority) as parameters. That is why the call has ten parameters. On UNIX, each setting is a separate small system call and can be made in any desired order between fork and exec.

3.3Process termination

Every process ends one day. The end may come at the process’s own wish, or through an error, or through the intervention of another process. However it ends, the kernel reclaims the process’s resources. Only one small piece, the exit status, is kept until the parent reads it. This section describes the kinds of termination, signals, and the zombie and orphan processes that arise from this small piece.

3.3.1Reasons for termination, exit(), and abort()

A process terminates for one of four reasons. The first two are voluntary: the process decides to end itself. The last two are involuntary: the process is stopped from outside.

Table 3.6: Reasons for process termination.
ReasonTypeExample
Normal exitvoluntaryreturn 0, exit(0); the compiler finished its job
Exit on errorvoluntaryfile not found → exit(1)
Fatal errorinvoluntaryinvalid memory access (SIGSEGV), division by zero (SIGFPE)
Intervention by another processinvoluntarykill(pid, SIGTERM); TerminateProcess() on Windows

The usual way of a voluntary exit is exit(status). Returning from main with return has the same effect, because the C runtime calls exit with the return value of main. exit is a C library function and does three things: it flushes the stdio buffers, runs the handlers registered with atexit, and then enters the kernel with the _exit system call. If _exit is called directly, the buffers are not flushed. This difference is used after fork to keep the child from writing the buffers a second time.

The exit status is an integer, but only its low 8 bits reach the parent. Meaningful values are therefore in the range 0–255. By convention 0 means success and every nonzero value denotes a kind of error. In the shell, the exit status of the last command is shown by $?, and operators such as && and || work according to this value.

abort(), by contrast, is an abnormal exit. The calling process sends itself the SIGABRT signal and dies from it. Depending on the system configuration, a core dump file may be produced. The assert macro calls abort when it fails. To terminate another process, the kill() system call is used.

However a process ends, the kernel does the same cleanup: it frees the process’s memory, closes its open files, and reclaims its other resources. Only the entry in the process table remains: a few pieces of information such as the PID, the exit status, and the CPU time used. This information is kept until the parent calls wait.

What happens to the children if the parent exits first varies from system to system. Some systems terminate all the children along with the parent; this is called cascading termination. On UNIX, by contrast, the children keep living and are attached to a new parent.

3.3.2Fatal errors

When a process performs an invalid operation, the processor detects it as an exception and hands control to the kernel. Depending on the type of exception, the kernel sends the process a signal. A signal is a small asynchronous message that tells a process an event has occurred. If the process has not installed a handler for that signal, the default action is applied; for fatal errors this action is to terminate the process.

Table 3.7: Fatal errors and signals.
ErrorSignal
Invalid or unauthorized memory accessSIGSEGV
Integer division by zeroSIGFPE
Illegal instructionSIGILL
Alignment or bus errorSIGBUS
Writing to a closed pipeSIGPIPE

Figure 3.14 shows the best-known example step by step. The program tries to write *p = 5 while p = NULL. Address 0 is not mapped to any page; the memory management unit (MMU) raises a page fault. The kernel sees that the address is invalid and sends the process SIGSEGV. If the process has not installed a handler for this signal, it terminates, and a core dump may be written.

p = NULL; *p = 5MMU: page faultkernel: invalid addressSIGSEGV is sentterminate + coreif no handler
Figure 3.14: The flow of a fatal error: writing through a NULL pointer → MMU page fault → the kernel sees that the address is invalid → SIGSEGV → if there is no handler, the process terminates and a core dump is taken.

A core dump is a snapshot of the process’s memory and registers at the moment it died. When a debugger opens it (gdb a.out core; coredumpctl on distributions that use systemd), you can see on which line and through which call chain the program died. This kind of examination is called post-mortem crash analysis.

Common mistake

Counting a memory leak as a fatal error. Memory that is not freed or files that are not closed do not kill the process by themselves; the process keeps running, and its resources are reclaimed anyway when it ends. In a long-lived server, however, a leak gradually exhausts memory. On Linux, if memory runs out, the OOM killer (out-of-memory killer) can pick one of the processes holding the most memory and terminate it with SIGKILL. Even then the process dies not because of the leak but because of this signal.

3.3.3Termination by signals

A process can terminate another process with the kill(pid, signal) system call. Its name is misleading: kill only sends a signal; the result of the signal need not be that the process dies. The command-line commands kill, pkill, and killall are user interfaces to this call.

Table 3.8: Signals used in process control (numbers are for x86 and ARM Linux).
SignalNo.Meaning
SIGTERM15terminate politely; the process can catch it and clean up (the default of kill)
SIGKILL9terminate by force; cannot be caught or ignored, no cleanup possible
SIGINT2Ctrl+C in the terminal
SIGTSTP20Ctrl+Z in the terminal (suspend); fg or bg resumes
SIGSTOP / SIGCONT19 / 18stop (cannot be caught) / resume

Signal numbers can vary from architecture to architecture; the values in the table are for x86 and ARM Linux. Portable code therefore uses names rather than numbers: kill(pid, SIGTERM) instead of kill(pid, 15). A typical use on the command line looks like this:

$ ps -e | grep writer
 1234 ?  00:00:03 writer
$ kill 1234       # SIGTERM
$ kill -9 1234    # SIGKILL
$ pkill writer    # by name
$ killall writer

A good habit is to send SIGTERM first and to move on to SIGKILL if the process does not respond. A program that catches SIGTERM deletes its temporary files, finishes interrupted writes, and closes its connections cleanly. SIGKILL gives no such chance: the process is stopped where it stands. Killing a database with kill -9 may require a recovery operation at the next startup.

Not every process can send a signal to every process. The sending process must belong to the same user as the target or be a privileged user (root). Otherwise kill returns with an “operation not permitted” error. This rule prevents one user from terminating another user’s processes.

3.3.4Zombie and orphan processes

The order in which the parent and child end gives rise to two special cases. Both are related to the wait call.

Definition 3.7

A zombie process is a process that has finished but whose parent has not yet collected its exit status with wait. Its memory and resources have been released; only its PID and exit status remain in the process table. An orphan process is a process that is still running whose parent terminated before it.

Figure 3.15 puts the two scenarios side by side. In the first scenario the parent (PID 100) and the child (PID 101) are running. The child ends with exit, but the parent has not yet called wait. The kernel cannot discard the child’s exit status, because the parent may ask for it later. The child becomes a zombie: in the ps output its state is Z and <defunct> appears next to its name. When the parent calls wait, it receives the status and the kernel deletes the entry. This step is called reaping; after it, no zombie remains.

In the second scenario the parent ends before the child. The child (PID 101) is still running and is now an orphan. The kernel does not leave the orphan without an owner: it attaches it to init or systemd (PID 1). If a subreaper process has been defined in the system, the orphan is attached to it; container managers and some session managers use this feature. If the child now calls getppid(), it gets 1 (or the PID of the subreaper). When the orphan ends, its new parent reaps it with wait. Because init does this job regularly, no zombies accumulate from orphans.

Scenario 1: the child ends firstparent · PID 100runningchild · PID 101ZOMBIE (Z) · exit code kept
Scenario 2: the parent ends firstsystemd · PID 1init / subreaperchild · PID 101adopted · PPID = 1
Figure 3.15: Zombie and orphan. (a) Scenario 1: the child (101) has finished but the parent (100) has not yet called wait; the child is a zombie and its exit code is kept. (b) Scenario 2: the parent finished first; the orphaned child was attached to systemd (PID 1), and its PPID is now 1.

Zombies use no memory or processor time, but they consume a limited resource: the PID. The number of PIDs on Linux is limited (the default upper limit is 32,768 or a larger value, depending on the system). A long-lived server that never calls wait and creates a child for every request accumulates thousands of zombies. Eventually no new process can be created and fork fails. Killing a zombie with kill does not help either, because it is already dead. The solution is either for the parent to call wait or for the parent to be terminated: then the zombies pass to init and are reaped.

A server that creates children usually catches the SIGCHLD signal in order to reap the children as they finish. The following skeleton shows this pattern:

#include <signal.h>
#include <sys/wait.h>

void reap(int sig) {
    (void)sig;
    while (waitpid(-1, NULL, WNOHANG) > 0)
        ;                       /* collect all finished children */
}

int main(void) {
    signal(SIGCHLD, reap);      /* run reap() when a child ends */
    /* ... server loop: fork() for each request ... */
    return 0;
}

The first argument −1 of waitpid means “any child.” With the WNOHANG option, waitpid returns 0 without waiting if there is no finished child. The loop collects all of several children that finish at the same time. This matters because if several signals of the same kind arrive one after another, they may be delivered as a single signal.

Common mistake

Confusing zombies with orphans, or assuming that the two are equally harmful. A zombie is a process that has finished but has not been reaped; an orphan is a process that is running but whose parent has died. Orphans are harmless, because init adopts them and reaps them when they end. Accumulating zombies, on the other hand, can lead to PID exhaustion; the source of the problem is a parent that does not call wait.

3.4Process states and the PCB

A process does not run continuously during its lifetime. Most of the time it waits for the processor or waits for an event to happen. The kernel must know what state each process is in at the moment and must keep everything about it in one place. This section describes the process states and the data structure in which this information is kept, the process control block.

3.4.1The five-state model

Definition 3.8

The process state describes the current activity of the process. In the five-state model, the states are as follows:

  • New: the process is being created.
  • Ready: the process is ready to run and is waiting for the processor.
  • Running: its instructions are being executed on the processor.
  • Waiting (blocked): it is waiting for an event (the completion of I/O, a signal, the termination of a child).
  • Terminated: its execution has finished.
admittedscheduler dispatchinterrupt / time slice expiredwait for I/O or eventI/O or event completionexitNewnewReadyreadyRunningrunningWaitingwaitingTerminatedterminated
Figure 3.16: The five-state process model and its six transitions: admitted, scheduler dispatch, interrupt or time slice expired, wait for I/O or event, I/O or event completion, exit.

The arrows in Figure 3.16 are the transitions between states. Each transition has a cause:

  • New → Ready (admitted): The kernel has set up the structures the process needs and has put the process in the ready queue.
  • Ready → Running (scheduler dispatch): The scheduler chooses this one among the ready processes and loads its context onto the processor. This step is called dispatch.
  • Running → Ready (interrupt): The time slice has expired or a higher-priority process has become ready. The process waits for nothing; its turn is simply over.
  • Running → Waiting (wait for event): The process has to wait for an event such as reading from disk, input from the keyboard, or the termination of a child. It gives up the processor on its own.
  • Waiting → Ready (event completion): The awaited event has occurred. The process does not run directly; it returns to the ready queue.
  • Running → Terminated (exit): The process has called exit or has been killed.

On a single core, only one process can be in the running state at any instant. On n cores, at most n processes can run. Most of the hundreds of processes in the system are ready or waiting. In reality, the bulk of processes are waiting: an editor waits for a key press, a server waits for a network request.

3.4.2State transitions step by step

To make the model concrete, let us follow a process’s lifetime from start to finish. Let the process read data from disk once and exhaust its time slice once.

Example 3.3
  1. New. The user started the program. The kernel is creating the PCB and allocating memory.
  2. New → Ready. The kernel admitted the process and put it in the ready queue.
  3. Ready → Running. The scheduler chose this process; its context was loaded.
  4. Running → Waiting. The process requested a read() from disk. Until the data arrives it has nothing to do, and it gives up the processor.
  5. Waiting → Ready. The disk interrupt arrived: the data is ready. The process does not run directly; it returns to the ready queue. At that moment another process may be running on the processor.
  6. Ready → Running. Chosen again.
  7. Running → Ready. The timer interrupt arrived: the time slice expired. This is preemptive scheduling; because the process is not waiting for anything, it goes to the ready state, not the waiting state.
  8. Ready → Running. Chosen again.
  9. Running → Terminated. The process called exit(). Until the parent calls wait, it stays in the process table as a zombie.

During this lifetime the process entered the ready queue 3 times (in steps 2, 5, and 7), waited once, and was chosen for the processor 3 times.

admittedscheduler dispatchinterrupt / time slice expiredwait for I/O or eventI/O or event completionexitNewnewReadyreadyRunningrunningWaitingwaitingTerminatedterminated
admittedscheduler dispatchinterrupt / time slice expiredwait for I/O or eventI/O or event completionexitNewnewReadyreadyRunningrunningWaitingwaitingTerminatedterminated
Figure 3.17: Two moments of the trace. (a) Step 4: the process called read() and moved to the waiting state. (b) Step 5: the event completed with the disk interrupt; the process returned to the ready state.
Common mistake

Thinking that a process whose awaited event has occurred moves directly to running. The model has no Waiting → Running arrow. When the event occurs, the processor most likely belongs to another process. The awakened process first enters the ready queue; the scheduler decides whether and when it gets the processor. Another common mistake is to put a process whose time slice has expired in the waiting state. A process whose time slice has expired waits for nothing; its turn is simply over, and it returns to the ready state.

3.4.3Process states in Linux

The five-state model is conceptual; real kernels merge some states and split others. On Linux the states are shown as a single letter in the STAT column of the ps command:

Table 3.9: Linux process states and their counterparts in the five-state model.
STATMeaningCounterpart in the model
Rrunning or ready to runRunning + Ready
Sinterruptible sleep (waiting for an event)Waiting
Duninterruptible sleep (usually disk I/O)Waiting
Tstopped (SIGSTOP, debugger)suspended
ZzombieTerminated (not reaped)
Iidle kernel thread—
$ ps -eo pid,stat,comm
  PID STAT COMMAND
    1 Ss   systemd
  890 Ss   sshd
 2105 Ss   bash
 2241 R+   ps
 2307 Z    writer <defunct>

In this output systemd, sshd, and bash are in state S: all of them are waiting for an event. The s at the end indicates that the process is a session leader. ps itself is R+: it is the only process running at that moment, and + indicates that it is in the foreground process group. The process named writer is in state Z; it is an unreaped zombie.

Linux does not distinguish between the ready and running states; both are shown as R. The waiting state, however, is split in two. A process in state S can be woken by a signal; for example, a program waiting for the keyboard ends at once with Ctrl+C. A process in state D does not respond to signals. This state is used for short disk operations whose interruption halfway would cause inconsistency. Processes stuck in D for a long time usually point to an unresponsive disk or network file system; they cannot be terminated even with kill -9.

3.4.4The process control block

When a process leaves the processor, the values in its registers must be saved somewhere; otherwise the process cannot continue where it left off. There are other things the kernel needs to know about a process: its state, priority, memory, open files. All of these are gathered in a single record.

Definition 3.9

The process control block (PCB) is the data structure that the kernel keeps for each process and that contains everything that needs to be known about that process. The structure formed by all the PCBs is called the process table. The part of the PCB that is saved when the process leaves the processor and loaded when it returns (the program counter and registers) is called the context.

process stateprocess identifier (PID)program counterregistersscheduling informationmemory management informationlist of open filesaccounting information (CPU time)• • •context(context)
Figure 3.18: The main fields of a PCB: process state, PID, program counter, registers, scheduling information, memory management information, list of open files, and accounting information. The program counter and registers make up the process’s context.

PCBs live in kernel memory. User processes cannot access them directly; they can read or change an item in their own PCB only through system calls. getpid() reads the PID from the PCB; nice() changes the priority; open() adds an entry to the list of open files. This restriction is the basis of security: a process cannot raise its own priority at will or reach another process’s files.

3.4.5PCB fields

Tanenbaum divides the fields in a process table entry into three groups according to the management task they serve. Table 3.10 gives this grouping.

Table 3.10: PCB fields according to Tanenbaum.
Process managementMemory managementFile management
registers · program counter · program status word (PSW) · stack pointer · process state · priority · scheduling parameters · PID · parent process · process group · signals · start time · CPU time used · children’s CPU time · next alarm timepointers to the text, data, and stack segments; today, the page table pointer and the list of memory regionsroot directory · working directory · file descriptors · user ID (UID) · group ID (GID)

Three fields in the table deserve a separate explanation:

  • Program status word (PSW): the register that holds the processor’s status flags (zero, overflow, carry …), the operating mode (user or kernel), and the interrupt permissions. Because the result of a comparison sits in these flags, the PSW is also part of the context. Even if the process is interrupted between a comparison and a conditional jump, it must still take the correct branch.
  • Process group: processes that are managed together. In the shell, a pipeline such as ls | grep x | wc -l forms a single group; when Ctrl+C is pressed, SIGINT goes to the whole group.
  • Next alarm time: if a process wants to be alerted after some time with alarm(seconds), the time at which the SIGALRM signal will be delivered is kept here.

The phrase “pointers to the text, data, and stack segments” in the memory management column reflects the old, segmented memory layout. Today the PCB points to the process’s page table and the list of memory regions. Figure 3.19 shows that the process table consists of entries accessed by PID and that each entry carries information from these three groups.

process table141210331034…array or list indexed by PIDprocess: state, registers, prioritymemory: page table pointerfile: open files, working directoryPCB (PID 1033)
Figure 3.19: The process table: each entry is a PCB. The entry for PID 1033 holds process information (state, registers, priority), memory information (page table pointer), and file information (open files, working directory).

3.4.6The PCB in Linux: task_struct

In Linux the PCB is called task_struct and is defined in the header file <linux/sched.h>. Linux represents processes and threads with the same structure; both are a “task” in the kernel’s eyes. The structure has several hundred fields; the most important ones are these:

struct task_struct {          /* <linux/sched.h> */
    pid_t pid;                     /* process ID */
    unsigned int __state;          /* process state */
    int prio;                      /* priority */
    struct sched_entity se;        /* CFS/EEVDF info */
    struct task_struct *parent;    /* parent process */
    struct list_head children;     /* children */
    struct files_struct *files;    /* open files */
    struct mm_struct *mm;          /* address space */
    /* ... hundreds more fields ... */
};

Each of the fields corresponds to a group in Table 3.10. pid carries the identifier, __state the state, and prio the priority. se is the information the scheduler keeps per process: how much CPU time the process has used and its place in the scheduler’s tree. parent and children build the process tree. files points to the open file table and mm to the address space (the page table and memory regions). It matters that mm and files are pointers: threads in the same process point to the same mm and files structures, and so share memory and files.

task_structPID 1task_structPID 2105task_structPID 2241currenttasks: doubly linked list
Figure 3.20: All task_structs are on a doubly linked list. current points to the task running on that core.

The kernel keeps all tasks on a doubly linked list (Figure 3.20). On each core, a pointer called current points to the task_struct of the task running at that moment. When a system call arrives, the kernel reaches the caller’s information through current. For example, getpid() roughly returns the value of current->pid (in reality it returns the ID of the thread group).

Kernel code changes over time, and the field names in textbooks can become outdated. In older kernels the state field was called long state and there was a separate field called time_slice. In current kernels the state is named __state. The time slice information has also been moved into the sched_entity structure.

3.5Scheduling infrastructure

The goal of multiprogramming is to keep the processor continuously busy. For this, the kernel must know which processes are waiting for the processor and which are waiting for an event, and must be able to hand the processor from one process to another. The policies that decide which process is chosen (first come first served, shortest job first, round robin …) are part of CPU scheduling. This section describes the mechanism on which policies are built: the queues, a simple model that measures the benefit of multiprogramming, and the context switch that transfers the processor between processes.

3.5.1Ready and wait queues

The scheduler chooses, among the ready processes, the one that will move to the processor. It has two goals: not to leave the processor idle, and to give the user fast responses. To make the choice, the processes must be kept in an orderly way. The kernel uses queues for this.

Definition 3.10

The ready queue is the list of processes that are in memory and waiting for the processor. Wait queues hold the processes that are waiting for a particular event (a disk finishing I/O, a child terminating, a packet arriving from the network). There is a separate wait queue for each type of event or each device.

ready queuehead · tailPCB 7PCB 2PCB 9disk I/O waithead · tailPCB 3PCB 14network / keyboard waithead · tailPCB 6CPUPCB 5 runningqueues are kept as linked lists of PCBs
Figure 3.21: Queues are kept as linked lists of PCBs. The ready queue holds PCBs 7, 2, and 9; the disk I/O wait queue holds PCBs 3 and 14; the network/keyboard wait queue holds PCB 6. PCB 5 is running on the processor.

Queues are not a separate data structure but links between PCBs. Each queue has two pointers to its head and tail, and each PCB has a field pointing to the next PCB. A process moving from one queue to another means that its PCB is removed from one list and added to another; the PCB itself is not copied. A process is in only one queue at a time, and the running process is in no queue.

Real systems use smarter structures than a simple FIFO list. Linux assigns a separate runqueue to each processor core. This way, cores do not wait for each other when choosing a ready process. The CFS scheduler and its successor EEVDF keep this queue as a red-black tree: finding the next process is fast, and inserting and removing a process takes O(log n).

3.5.2The queueing diagram

The lifetime of a process can also be drawn as a journey among queues. In the queueing diagram of Figure 3.22, rectangles stand for queues, the circle for the processor, and the arrows for transitions.

ready queueCPUterminate (exit)I/O wait queueI/O requesttime slice expiredwait for child to finishcreate child (fork)interrupt wait queuewait for interrupt
Figure 3.22: The queueing diagram of process scheduling. The process moves from the ready queue to the processor; from there it leaves by one of four routes: an I/O request, expiry of the time slice, creating a child and waiting, or waiting for an interrupt. In the end it leaves the system with exit.

The journey proceeds as follows. A new process is added to the end of the ready queue and waits its turn. When the scheduler chooses it, it runs on the processor. A running process can leave the processor by one of four routes:

  • It makes an I/O request and moves to the relevant I/O wait queue. When the I/O completes, it returns to the ready queue.
  • Its time slice expires; the timer interrupt takes it off the processor and it returns directly to the ready queue. On this route there is no wait queue.
  • It creates a child and calls wait(); it waits until the child ends.
  • It waits for an interrupt or event; for example, the expiry of a sleep() time or the arrival of a network packet.

The process repeats this cycle until it finishes. In the end it leaves the system with exit(); its PCB is deleted when the parent calls wait. The diagram is the state model of Figure 3.16 drawn with queues: the ready queue corresponds to the “Ready” state, the wait queues to the “Waiting” state, and the processor to the “Running” state.

3.5.3CPU-bound and I/O-bound processes

Almost every process alternates between two kinds of activity: it computes on the processor, then waits for I/O, then computes again. Intervals of uninterrupted computation are called CPU bursts. Processes fall into two groups according to the length of these bursts (Figure 3.23).

(a) CPU-bound(b) I/O-boundCPU burstI/O waittime
Figure 3.23: (a) CPU-bound process: long CPU bursts, rare I/O. (b) I/O-bound process: short CPU bursts, frequent I/O waits.
Definition 3.11

A CPU-bound process spends most of its time computing; it has long CPU bursts and rare I/O requests. Compiling, video encoding, and scientific computation are of this kind. An I/O-bound process spends most of its time waiting for I/O; its CPU bursts are short. A text editor, a web server, and a database client are of this kind.

The length of the bursts, not the duration of the I/O, determines which group a process belongs to. An I/O-bound process, after its data arrives, does a little computation and immediately asks for new I/O. Because processors have improved much faster than disks, more processes have become I/O-bound over time. The same computation takes less time each year, but waiting for the disk or the network does not shrink at the same rate.

This distinction matters for the scheduler. When an I/O-bound process becomes ready, it should get the processor at once; it finishes its short job and starts a new I/O, keeping the disk busy. If this process waits in the ready queue behind a long CPU-bound process, the disk sits idle and the user gets a slow response. A good system mixes the two kinds in balance: CPU-bound processes keep the processor busy, and I/O-bound processes keep the devices busy.

3.5.4Modeling multiprogramming

How many processes should be kept in memory? A simple probabilistic model gives a rough but instructive answer to this question.

Theorem 3.1 (Multiprogramming model)

Let each process spend a fraction p of its time waiting for I/O, and let the processes be independent. If there are n processes in memory, the CPU utilization is

CPU utilization = 1 − pn

Here n is called the degree of multiprogramming.

The processor is idle only when all the processes in memory are waiting for I/O at the same time; if at least one is ready, the processor runs. The probability that a process is waiting at any moment is p. Because the processes are independent, the probability that all n are waiting at once is the product of the probabilities: p · p · … · p = pn. Since the probability that the processor is idle is pn, the probability that it is busy is 1 − pn.

∎

204060801000246810number of processes in memory (degree of multiprogramming) nCPU %20% I/O wait50% I/O wait80% I/O wait
Figure 3.24: CPU utilization as a function of the degree of multiprogramming; three curves for 20%, 50%, and 80% I/O wait. The higher the wait fraction, the more processes are needed to reach the same utilization.

The curves in Figure 3.24 show two lessons of the model. First, for I/O-bound processes (p large), a single-programmed system is wasteful. With p = 0.8, utilization with a single process is only 20%; with 4 processes it rises to 59%, and with 10 processes to 89%. Second, the curve gradually flattens. Each new process gains less than the one before, because utilization never reaches 100%.

The model is crude. It assumes that processes are independent; yet processes waiting for a single disk are served in turn, and their waiting is correlated. Still, the model is useful for memory planning: when memory is increased, one can quickly estimate how many more processes will fit and how much this raises utilization. For example, if each process uses 2 GB and p = 0.8, adding 8 GB to an 8 GB machine (4 processes) raises utilization from 59% to 83%. The next 8 GB raises it only to 93%.

Example 3.4

Processes spend 60% of their time waiting for I/O. (a) What is the CPU utilization with 3 processes? (b) How many processes must be in memory for utilization to be at least 95%?

  1. (a) p = 0.6 and n = 3: 0.63 = 0.216. Utilization is 1 − 0.216 = 0.784, that is, 78.4%.
  2. (b) Inequality. We need 1 − 0.6n ≥ 0.95, which means 0.6n ≤ 0.05.
  3. Trial. 0.65 = 0.07776 → utilization 92.2%; not enough. 0.66 = 0.046656 → utilization 95.3%; enough.
  4. Check with logarithms. n ≥ ln 0.05 / ln 0.6 ≈ 5.86. Because n is an integer, it is rounded up: at least 6 processes are needed.
Common mistake

Rounding down the value found with logarithms. Rounding the result ln 0.05 / ln 0.6 ≈ 5.86 down to 5 leaves utilization at 92.2% and the condition is not met. A similar trap is misreading p: p is the I/O wait fraction, not the CPU utilization fraction. If it is said that “processes use the processor 25% of the time,” take p = 0.75.

3.5.5Code trace: CPU utilization 1 − pn

It is easy to produce the values of the model as a table with a loop. The program in the slides computes the values for n = 1…5 with p = 0.8:

double p = 0.8;      /* I/O fraction */
double pn = 1.0;
for (int n = 1; n <= 5; n++) {
  pn = pn * p;       /* all waiting */
  double util = 1 - pn;
  printf("n=%d %.0f%%\n", n, util * 100);
}

The trick of the program is that it does not recompute pn from scratch in every round. The variable pn holds the value from the previous round and is multiplied by p once per round. Thus in round n, pn = pn. The %% in printf prints a percent sign; %.0f prints the number with no decimals, rounding it.

Table 3.11: Trace of the loop (p = 0.8).
npnutilOutput lineIncrease (points)
10,80,2n=1 20%—
20,640,36n=2 36%16
30,5120,488n=3 49%12,8
40,40960,5904n=4 59%10,24
50,327680,67232n=5 67%8,19

The last column of the table shows the model’s “diminishing returns” property with numbers. The second process raises utilization by 16 points; the fifth only by 8.19 points. In fact each increase is exactly 0.8 times the previous one: in going from n to n + 1, the increase is pn − pn+1 = pn(1 − p). That 48.8 is printed as 49% and 67.232 as 67% also comes from the rounding of %.0f.

%0%50%100n=1%20n=2%36n=3%49n=4%59n=5%67emptyidle probability pⁿ = 0.3277
Figure 3.25: CPU utilization for n = 1…5 when the loop ends: 20%, 36%, 49%, 59%, 67%. The upper part of each bar is the fraction in which the processor stays idle (pn).

3.5.6Context switching

When the scheduler chooses a process, the processor must switch to that process. This switch requires saving the state of the process currently running on the processor somewhere and loading the state of the chosen process into the processor.

Definition 3.12

A context switch is the operation of transferring the processor from one process to another. The kernel saves the running process’s context (program counter, registers, PSW) into its PCB, loads the chosen process’s context from its own PCB, and switches the address space to that of the new process.

process P₀operating systemprocess P₁interrupt or system callsave state into PCB₀load state from PCB₁save state into PCB₁load state from PCB₀time
Figure 3.26: Context switch between two processes. While P₀ runs, an interrupt or system call arrives; the kernel saves P₀’s state into PCB₀ and loads P₁’s from PCB₁. Later the same work is done in the opposite direction. No user work is done during the gray intervals.

Figure 3.26 shows two switches on a time axis. While P₀ runs, an interrupt or system call arrives. The processor switches to kernel mode, and P₀’s program counter and registers are saved into PCB₀. The scheduler chooses P₁; P₁’s context is loaded from PCB₁ and the address space changes. While P₁ runs, P₀ is idle: it is in the ready or waiting state. At the next interrupt, P₁’s state is saved into PCB₁, the contents of PCB₀ are restored, and P₀ resumes where it left off.

The gray intervals in the figure are the cost of the context switch. During that time the processor is working, but no user program makes progress. A context switch is therefore pure overhead.

3.5.7Code trace: context switching

In real kernels the context switch is written in assembly, because the registers must be accessed directly. Its logic, however, can be modeled in a few lines of C. In the program below, the array P is the process table; each PCB has three registers (pc, sp, r1) and a state letter. The global variables pc, sp, and r1 stand for the processor’s registers.

struct pcb { int pc, sp, r1; char state; };
struct pcb P[2];   /* process table */
int pc, sp, r1;    /* CPU registers */
void context_switch(int from, int to) {
  P[from].pc = pc;  P[from].sp = sp;  /* save */
  P[from].r1 = r1;  P[from].state = 'R';
  pc = P[to].pc;  sp = P[to].sp;  /* load */
  r1 = P[to].r1;  P[to].state = 'X';
}
/* interrupt */  context_switch(0, 1);
/* ... P1 runs ... */
/* interrupt */  context_switch(1, 0);

context_switch(from, to) consists of two halves. The first half saves the registers of the old process (from) into its PCB and sets its state to 'R' (ready). The second half loads the registers of the new process (to) into the processor and sets its state to 'X' (running). Initially P₀ is running: pc = 104, sp = 896, r1 = 8. The last state of P₁ is stored in PCB₁: pc = 340, sp = 500, r1 = 2.

Table 3.12: Trace of the context switch. Values are written in the order pc/sp/r1; “—” marks a field that has not yet been saved.
StepLineCPUPCB₀PCB₁Explanation
110104/896/8 (P₀)—/—/— X340/500/2 Rtimer interrupt; the kernel decides to switch to P₁
25104/896/8104/896/— X340/500/2 RP₀’s pc and sp have been saved
36104/896/8104/896/8 R340/500/2 Rr1 has been saved too; P₀ is ready
47340/500/8104/896/8 R340/500/2 RP₁’s pc and sp have been loaded
58340/500/2 (P₁)104/896/8 R340/500/2 Xr1 has been loaded; P₁ is running
611352/492/5104/896/8 R340/500/2 XP₁ has run a few instructions; PCB₁ is no longer current
712352/492/5104/896/8 R340/500/2 Xnew interrupt; the switch back to P₀ is about to happen
85352/492/5104/896/8 R352/492/2 XP₁’s pc and sp have been saved
96352/492/5104/896/8 R352/492/5 Rr1 has been saved; P₁ is ready
107104/896/5104/896/8 R352/492/5 Rpc and sp have been loaded from PCB₀
118104/896/8 (P₀)104/896/8 X352/492/5 Rr1 = 8; P₀ continues where it was interrupted

Three intermediate states in the trace deserve attention. In step 4 the processor’s registers are mixed: pc and sp belong to P₁, while r1 still belongs to P₀. This half-done state shows that a context switch must be carried out without interruption. Real kernels disable interrupts during this time. In step 6, the values in PCB₁ (340/500/2) are out of date; P₁’s real state is only in the processor. The PCB is updated not while the process runs but when it leaves the processor. In step 11, P₀ continues from exactly the state in which it was interrupted, from pc = 104, and does not notice that it was interrupted.

The model simplifies reality. A real processor has dozens of general-purpose registers, floating-point and vector registers, and the PSW. The address space also changes: the processor’s page table register is loaded so that it points to the new process’s table.

3.5.8Limited direct execution

The context switch leaves one question unanswered: while the processor is running a user program, how does the kernel get control back? The kernel is also a program, and the processor runs only one thing at a time. If the user program enters an infinite loop, the kernel’s code may never run.

One solution could be to run the user program step by step in an interpreter, but that is far too slow. The route operating systems take is limited direct execution. The program runs directly on the processor at full speed. But it has two limits: it cannot do privileged work itself and must ask the kernel; and it cannot hold the processor as long as it likes, because the kernel takes it back by force. Figure 3.27 shows this arrangement in five steps.

  1. At boot (in kernel mode). The operating system tells the hardware which code to run on which event: it sets up the trap and interrupt table. It then starts the timer, which will raise an interrupt every few milliseconds. Both operations use privileged instructions; the user program cannot change them.
  2. A is running. Process A runs directly on the processor in user mode; there is no interpreter in between. For a privileged job such as opening a file, it must trap into the kernel with a system call.
  3. Timer interrupt. Even if A is in an infinite loop, the interrupt arrives. The hardware saves A’s registers on the kernel stack, switches to kernel mode, and jumps to the operating system’s interrupt handler. Control is now with the operating system.
  4. The scheduler chooses B. Because A’s time slice has expired, the operating system decides to switch to B. The switch() routine writes A’s context into PCB(A), loads B’s, and moves to B’s kernel stack.
  5. Return from trap. The return-from-trap instruction loads B’s registers as if B were returning from where it was interrupted, and switches to user mode. Now B runs.
OS (kernel mode)HardwareProgram (user mode)bootrunningset up the trap tablestore handler addressesstart the timerraise an interrupt every few msA is running (directly on the CPU)timer interruptregisters(A) → kernel stackthe scheduler chooses Bswitch(): A → PCB(A), load Breturn-from-trapregisters(B), user modeB is running
Figure 3.27: Limited direct execution. At boot the operating system sets up the trap table and the timer. While A runs directly on the processor, the timer interrupt gives control to the operating system; switch() moves from A to B, and with the return from trap B starts to run.

The timer interrupt is the backbone of this arrangement. Without the interrupt, the operating system could take control back only when the process made a system call of its own accord. This approach is called cooperative multitasking, and Windows 3.x and old versions of Mac OS worked this way. On these systems, a single program that entered an infinite loop would lock up the entire machine; the remedy was to restart it.

3.5.9The cost of a context switch

A context switch does not come free. While moving to another process, the processor must save the old process’s state and load the new one’s, and no useful work is done during this time. The larger the PCB and the more complex the operating system, the longer the switch takes. The cost is of two kinds:

  • Direct cost: saving and loading the registers and running the scheduler code. On current Linux it is typically a few microseconds.
  • Indirect cost: the “cooling” of the cache and the TLB (translation lookaside buffer, a small cache that holds address translations). In its first moments the new process cannot find its data in the cache and suffers many cache misses. This indirect cost is often larger than the direct cost.

Hardware helps to reduce this cost. Some processors have several register sets; a switch amounts to changing a pointer that selects the set. An address-space tag added to TLB entries (ASID on ARM, PCID on x86) removes the need to flush the TLB at every switch: the entries of different processes are told apart by their tags.

The cost of a context switch plays a direct role in choosing the time slice. If the slice is chosen too short, most of the processor’s time goes to switches; if too long, processes wait a long time for their turn.

Example 3.5

A context switch takes s = 0.05 ms. There are 3 CPU-bound processes running in turn in the ready queue, and each uses its full slice of q = 4 ms. (a) What percentage of processor time goes to switches? (b) At most how long does a process wait between two of its slices?

  1. Identify one cycle. Each slice is followed by a switch. So in every interval of q + s = 4.05 ms, 0.05 ms is overhead.
  2. (a) The overhead fraction is s / (q + s) = 0.05 / 4.05 ≈ 0.0123, that is, about 1.23%.
  3. (b) When process A finishes its slice, a switch happens and B runs; one more switch and C runs; another switch and A starts again. A’s wait is 3 switches and 2 slices: 3 · 0.05 + 2 · 4 = 8.15 ms.
  4. Generalization. For k processes the wait is k · s + (k − 1) · q. As the slice gets smaller, the wait gets shorter but the overhead fraction grows.

3.5.10Interrupt handling

Most context switches begin with an interrupt. Tanenbaum summarizes in eight steps what happens at the lowest layer of the operating system when an I/O interrupt arrives:

  1. The hardware saves the program counter, the PSW, and a few registers on the stack. The interrupt request is accepted not in the middle of an instruction but at an instruction boundary. The processor switches to kernel mode.
  2. The hardware loads the new program counter from the interrupt vector. The interrupt vector is the table that holds the handler’s address for each type of interrupt. The operating system fills in this table at boot.
  3. An assembly routine saves the registers. The registers that the hardware did not save are written to the current process’s PCB or the kernel stack.
  4. An assembly routine sets up a new stack. The interrupt handler runs not on the user’s stack but on the kernel stack.
  5. The interrupt service routine written in C runs. It typically reads the data coming from the device and places it in a buffer. If a process is waiting for this data, it moves that process to the ready state.
  6. The scheduler chooses the next process. If the awakened process has a higher priority than the interrupted one, it may be chosen. In that case the interrupt turns into a context switch.
  7. The C routine returns to the assembly code.
  8. An assembly routine starts the chosen process. The process’s registers and memory mapping are loaded and the processor returns to user mode.

The division of labor among the steps is remarkable. The hardware does the first two steps, because at that moment there is no safe environment in which any software could run. Steps 3, 4, and 8, which touch the registers directly, are written in assembly. The real work is done in portable C code. This path, which starts with an interrupt, lets the interrupted process continue without noticing it was interrupted; or, if the scheduler so decides, hands the processor to another process.

3.6Interprocess communication

Separate address spaces prevent one process’s error from spreading to another. But the same separation makes it hard for processes to work together: one process cannot read another’s variable. Cooperating processes use the facilities that the operating system provides to exchange data. This section describes the two basic models of these facilities, shared memory and message passing, and then UNIX pipes and sockets.

3.6.1Independent and cooperating processes

A process is independent if it does not affect other processes and is not affected by them. Processes that share data or affect one another’s work are cooperating. There are four reasons for processes to cooperate:

  • Information sharing: Several applications may want to access the same data, for example text copied to a clipboard.
  • Speedup: A large job is divided into pieces, and the pieces are processed in parallel on different cores.
  • Modularity: The system is built from small processes that each do a single job.
  • Security and isolation: Risky work is done in separate processes with restricted privileges; Chrome’s renderer processes are an example.
Definition 3.13

Interprocess communication (IPC) is the general name for the mechanisms that let cooperating processes exchange data and coordinate their actions. It has two basic models: shared memory and message passing.

IPC must answer three questions. The first is obvious: how does one process pass information to another? The other two are subtler. The second is that processes must not get in each other’s way. If two reservation processes both see the last free seat at the same time and both sell it, two tickets are issued for the same seat. The third is ensuring the correct order among dependencies. One must not fire before aiming; data must not be consumed before it is produced.

The last two questions require synchronization. Uncontrolled access to shared data makes the result depend on the order in which the processes run. This situation is called a race condition. The same questions apply to threads that share the same address space.

3.6.2Shared memory and message passing

The two models differ in where the data passes between processes (Figure 3.28).

(a) shared memory(b) message passingprocess Ashared regionmapped into both address spacesprocess Bkernelwriteprocess Aprocess Bkernel: message queuem₀m₁m₂
(a) shared memory(b) message passingprocess Ashared regionmapped into both address spacesprocess Bkernelprocess Aprocess Bkernel: message queuem₁m₂m₃receive() → m₀
Figure 3.28: Two IPC models. (a) Shared memory: the kernel maps a region into the address spaces of two processes, and A writes to the region directly. (b) Message passing: the kernel keeps the messages in its own queue; B takes the next message (m₀) with receive().

In shared memory, the kernel creates a memory region and maps it into the address spaces of two processes. A system call is needed only for the setup. After that, A writes to the region with an ordinary memory write, and B reads with an ordinary memory read. The kernel does not come into play in this exchange at all, which is why shared memory is very fast. The price is this: the kernel does not control who writes when. The processes must provide the coordination themselves, with tools such as locks or semaphores.

In message passing, A sends a message with a send(m) call; the kernel copies the message into its own queue. B takes the next message with a receive() call; this time the kernel copies the message into B’s memory. Every message involves at least one system call and two copies; message passing is therefore slower than shared memory. Its gain is that the coordination lives in the kernel: a process that wants to read from an empty queue is made to wait, and a message is never read half-way. The same interface can also work over a network, whereas shared memory is possible only for processes on the same machine.

Table 3.13: Comparison of shared memory and message passing.
CriterionShared memoryMessage passing
Role of the kernelonly at setupon every message
Copyingnonethe message is copied to the kernel and to the receiver
Coordinationthe processes’ responsibilityprovided by the kernel
Suitable whenlarge data on the same machinesmall messages; distributed systems

3.6.3POSIX shared memory

POSIX sets up shared memory with an object that is named like a file. The code below contains the parts of two separate processes: the upper one is the producer, the lower one the consumer.

/* producer */
int fd = shm_open("/os03", O_CREAT|O_RDWR, 0600);
ftruncate(fd, 4096);
char *p = mmap(NULL, 4096, PROT_READ|PROT_WRITE,
               MAP_SHARED, fd, 0);
strcpy(p, "hello");     /* direct write */

/* consumer (another process) */
int fd = shm_open("/os03", O_RDONLY, 0);
char *p = mmap(NULL, 4096, PROT_READ,
               MAP_SHARED, fd, 0);
printf("%s\n", p);
shm_unlink("/os03");    /* remove */

The setup consists of three steps. shm_open creates a shared memory object named /os03 or opens the existing one, and returns a file descriptor. On Linux this object appears as a file under /dev/shm. ftruncate sets the size of the object to 4096 bytes. mmap maps the object into the process’s address space and returns the starting address of the mapping. The MAP_SHARED flag is important: writes to this region are visible in every process that maps the same object.

After setup, shared memory is ordinary memory. The producer writes "hello" directly with strcpy; no system call is involved. The consumer opens the same object read-only, maps it, and reads it with printf. When finished, shm_unlink deletes the object’s name; the object disappears when the last process that has mapped it lets go.

producer processcodedatap = 0x7f3a…stackconsumer processcodedatap = 0x7f91…stack/os03 (4096 B)"hello"physical memory (/dev/shm)mmapmmap
Figure 3.29: Two processes map the same physical region (/os03, 4096 bytes) to different virtual addresses in their own address spaces: p = 0x7f3a… in the producer and p = 0x7f91… in the consumer. Both see the same "hello" data.

Figure 3.29 also shows a subtle point: the values of p in the two processes are different. The region can be mapped to a different virtual address in each process’s address space. Storing a pointer in a shared region is therefore dangerous; an address that is valid in one process may be meaningless in the other. Shared data structures use an offset from the start of the region instead of a pointer.

Common mistake

Assuming that shared memory provides coordination by itself. In the example code, if the consumer runs before the producer writes, it sees the region empty and prints an empty string. Worse, if the consumer reads while the producer is writing, it may see half-written data. In real code, access to the region must be regulated with a semaphore or a lock. There is also an older interface for this: System V’s shmget and shmat calls. The logic is the same; only the objects are named with a numeric key instead of a file name.

3.6.4Message-passing design

Message passing has two basic operations: send(message) and receive(message). Before two processes can communicate, a communication link must be established between them. Four questions stand out in the design of this link.

Table 3.14: Dimensions of message-passing design.
DimensionOptions
Physical linkshared memory, hardware bus, network
Namingdirect (the process’s name) · indirect (mailbox or port)
Synchronous / asynchronousblocking (synchronous): the sender waits until the message is received, the receiver waits until a message arrives · nonblocking (asynchronous): the call returns immediately
Bufferingzero capacity (the sender waits: rendezvous) · bounded capacity (the sender waits if the queue is full) · unbounded capacity (the sender never waits)

Buffering is how many messages the link can hold. A zero-capacity link has no place to store a message. The sender waits until the receiver calls receive, and the message is transferred directly at the moment the two processes meet. In a bounded-capacity link, up to N messages can wait in the queue; if the queue is full, the sender waits. Unbounded capacity is conceptual; in reality memory is always limited.

Definition 3.14

Rendezvous is message passing in which both send and receive are blocking. The sender waits until the receiver takes the message; the receiver waits until a message arrives. The transfer happens when both processes are ready at the same time.

Rendezvous solves the producer–consumer problem by itself. The producer cannot send a new message until the consumer has taken one; the consumer cannot take a message that has not been produced. The programmer need not keep a lock or a counter separately. Examples in real systems include POSIX message queues (mq_send, mq_receive), the ports of the Mach kernel underlying macOS, and Windows’ ALPC (Advanced Local Procedure Call) mechanism.

Example 3.6

A message queue has a capacity of 2; send and receive are blocking. The consumer has not yet called receive, and the producer wants to send messages m₁, m₂, and m₃ in a row. What happens?

  1. send(m₁): The queue is empty; m₁ is copied into the queue and the call returns immediately. There is 1 message in the queue.
  2. send(m₂): There is room; m₂ is added. The queue is now full (2/2).
  3. send(m₃): There is no room in the queue; the producer moves to the waiting state.
  4. The consumer calls receive(): It takes m₁ (the message queue is FIFO). One slot becomes free; the kernel wakes the waiting producer and m₃ is added to the queue. The queue holds m₂ and m₃.

If the capacity were zero, the producer would wait at the very first send, and when the consumer called receive, m₁ would be transferred directly.

3.6.5Direct and indirect communication

The naming question is how the sender says whom it is sending the message to (Figure 3.30).

direct: send(Q, m)PQone link · one pair of processesindirect: send(A, m)mailbox Aport / queuePQRmany processes · many links
Figure 3.30: On the left, direct communication: P sends to Q by name; the link belongs to a single pair of processes. On the right, indirect communication: P, Q, and R communicate through mailbox A; one link can belong to many processes, and one pair can have many links.

In direct communication, each process names the other party: send(P, m) sends to P, and receive(Q, m) receives from Q. The link is established automatically and belongs to exactly one pair of processes. There is a single link between each pair, and the link is usually bidirectional. The weakness of this approach is that process names are embedded in the code: if a process restarts and gets a new identity, all the code that names it must change.

In indirect communication, messages are sent to and received from a mailbox or port: send(A, m), receive(A, m). Each mailbox has a unique identity; processes that share the same mailbox can communicate. A link can belong to more than two processes, and a pair of processes can communicate through several mailboxes. A link can be unidirectional or bidirectional. This flexibility raises a question too: when P puts a message in a mailbox and Q and R call receive at the same time, who gets the message? Systems solve this either by allowing only one receiver at a time or by choosing the receiver themselves.

3.6.6Pipes

A pipe is UNIX’s oldest and most widely used IPC tool. A pipe is a FIFO buffer kept in the kernel with two ends. The bytes written at one end are read from the other end in the same order (Figure 3.31).

parentfd[0] closed · fd[1] writeschildfd[0] reads · fd[1] closedpipe: FIFO buffer in the kernelwrite(fd[1])read(fd[0])write end → read end (one-way)
Figure 3.31: An ordinary pipe: the parent writes to the write end fd[1], and the child reads from the read end fd[0]. The data passes through the FIFO buffer in the kernel and flows in one direction. Each process closes the end it does not use.

Four questions are asked when designing a pipe. Is the flow unidirectional (simplex) or bidirectional? If bidirectional, can both directions be used at the same time (full duplex) or only in turn (half duplex)? Is a parent–child relationship required between the communicating processes? Can the pipe be used over a network? The two kinds of pipe answer these questions differently.

Table 3.15: Ordinary and named pipes.
Ordinary (unnamed)Named (FIFO)
Accessonly the creating process and its childrenany process that knows the file name
Directionone-wayUNIX: half duplex; Windows: full duplex
Lifetimeends when the processes close itcreated with mkfifo; stays in the file system
NetworknoUNIX: no; Windows: yes

An ordinary pipe has no name; it is accessed only through file descriptors. These descriptors can pass to other processes only by inheritance through fork. An ordinary pipe is therefore used between related processes. A named pipe, on the other hand, carries a name in the file system (mkfifo /tmp/channel). Two processes that do not know each other can communicate by opening this name. Although FIFOs on UNIX can be used in both directions, in practice a separate FIFO is opened for each direction, because if two processes write to the same FIFO the data gets mixed up.

3.6.7Code trace: pipe() and fork()

The following program shows the parent sending "welcome" to the child over a pipe:

int main(void) {
  int fd[2];
  char buf[32];
  pipe(fd);
  pid_t pid = fork();
  if (pid == 0) {   /* child: reads */
    close(fd[1]);
    ssize_t n = read(fd[0], buf, sizeof buf - 1);
    buf[n] = '\0';
    printf("child got: %s\n", buf);
    close(fd[0]);
    return 0;
  }
  close(fd[0]);     /* parent: writes */
  write(fd[1], "welcome", 7);
  close(fd[1]);
  wait(NULL);
  return 0;
}

The call pipe(fd) creates a pipe and returns two descriptors: fd[0] is the read end and fd[1] is the write end. Because numbers 0, 1, and 2 belong to the standard input, output, and error streams, the lowest free numbers are 3 and 4. Then comes fork, and the child inherits both ends. Thus both ends of the pipe are open in both processes. Each process closes the end it will not use: the child the write end, the parent the read end. Let the parent’s PID be 1234 and the child’s 1235.

Table 3.16: Trace of pipe() + fork(). In the “Open ends” column, P stands for the parent and C for the child.
StepLineEventOpen endsBufferOutput
14pipe(fd): fd[0] = 3, fd[1] = 4P: 3, 4empty
25fork: the child inherits the endsP: 3, 4 · C: 3, 4empty
37the child closes the write endP: 3, 4 · C: 3empty
48the child calls read: the pipe is empty → waitingP: 3, 4 · C: 3empty
514the parent closes the read endP: 4 · C: 3empty
615the parent writes 7 bytes; the child wakes upP: 4 · C: 3welcome
716–17the parent closes the write end and waits with waitC: 3welcome
88read returns 7; n = 7C: 3empty
99–10buf[7] = '\0'; the child printsC: 3emptychild got: welcome
1011–12, 17–18the child closes the read end and exits; the parent returns from wait and ends——

The order of the steps in the trace may vary with scheduling. For example, the parent may write before the child calls read; then the child gets the data without waiting at all. The output is the same in every order, because only the child prints and the data flows along a single path.

Three details of the trace show the rules of pipes. First, a process that reads from an empty pipe is made to wait (step 4). Second, writes of up to PIPE_BUF bytes (4096 bytes on Linux) are not split: they are written either completely or not at all. This way the small messages of two processes writing to the same pipe do not get mixed together. Third, read returns at most as many bytes as requested but may return fewer. The program asked for 31 bytes (sizeof buf - 1), there are 7 bytes in the pipe, and read returns 7. The returned value is used to put '\0' at the end of the string.

Closing the write end matters too. read returns 0 when the pipe is empty and no process has a write end open; this means end of file (EOF). As long as a write end stays open somewhere, the reader waits, thinking “maybe more data will come.”

Common mistake

Not closing unused pipe ends. Suppose the child uses a loop that reads until EOF and the parent does not call close(fd[1]). Then even when the pipe empties, a write end remains open and read never returns 0. The child waits forever, and the parent waits for the child in wait: the program deadlocks. The child not closing its own write end has the same result, because that end also counts as “an open writer.” There is a rule in the opposite direction too: a process that writes to a pipe whose read end is completely closed receives a SIGPIPE signal and by default terminates.

3.6.8Pipelines in the shell

When ls | wc -l is typed in the shell, the output of ls becomes the input of wc, and the number of files in the directory appears on the screen. The shell does this by combining the pipe with redirection:

int fd[2]; pipe(fd);
if (fork() == 0) { dup2(fd[1], 1); close(fd[0]); close(fd[1]);
                   execlp("ls", "ls", NULL); }
if (fork() == 0) { dup2(fd[0], 0); close(fd[0]); close(fd[1]);
                   execlp("wc", "wc", "-l", NULL); }
close(fd[0]); close(fd[1]); wait(NULL); wait(NULL);
bashpipe(), 2 × fork(), waitlsdup2(fd[1], 1) → stdoutwc -ldup2(fd[0], 0) → stdinpipe (64 KiB buffer)both processes must close the ends they do not use; otherwise wc never sees EOF
Figure 3.32: The ls | wc -l pipeline. The shell creates one pipe and two children; the standard output of ls is redirected to the write end of the pipe, and the standard input of wc to the read end. On Linux the pipe buffer is 64 KiB by default.

The shell first creates a pipe and then calls fork twice. The first child connects its standard output to the write end of the pipe with dup2(fd[1], 1). dup2(old, new) makes the descriptor numbered new a copy of old; if new is open, it closes it first. The child then closes both pipe descriptors, because from now on it will do its job through number 1. Then it turns into ls. The second child does the same for the read end and standard input (0) and turns into wc -l. The shell closes its own ends and waits for the two children.

Here again the closing rule is decisive. If the shell or the second child kept the write end open, then even when ls finished and closed its own end, an open writer would remain on the pipe. wc would never see EOF and could never finish counting lines. Error checks have been left out of the code in the slides for brevity; a real shell checks the return value of every call.

The strength of this design is that programs do not notice the pipe. ls writes to standard output and wc reads from standard input; for them there is no difference between a terminal, a file, and a pipe. Thus small programs that know nothing of each other can be chained with | in the shell to do big jobs. The UNIX philosophy of “each program should do one thing well” rests on this infrastructure.

3.6.9Sockets

Pipes connect processes on the same machine. Sockets are used for processes on different machines to communicate.

Definition 3.15

A socket is an endpoint of communication. A network socket is identified by the combination of an IP address and a port number; for example 161.25.19.8:80. Communication is always between a pair of sockets.

client 146.86.5.20socket146.86.5.20:1625web server 161.25.19.8socket161.25.19.8:80TCP connectionephemeral port ↔ well-known port
Figure 3.33: Communication with sockets. The client (146.86.5.20) establishes a TCP connection from an ephemeral port (1625) to the well-known port 80 of the web server (161.25.19.8).

The IP address distinguishes the machine, and the port distinguishes the service on the machine. A web server listens on port 80; when the client connects, the operating system assigns the client an ephemeral port (1625 in the figure). The connection is defined by the pair of sockets 146.86.5.20:1625 and 161.25.19.8:80. A second connection opened from the same machine to the same server gets another ephemeral port, and the two connections do not get mixed up.

Ports below 1024 are reserved for well-known services: SSH 22, HTTP 80, HTTPS 443. Starting to listen (bind) on these ports as a server requires privilege; this prevents an ordinary user from setting up a fake SSH server. The address 127.0.0.1 (::1 in IPv6) is the loopback address and points to the same machine; processes on the same machine can also communicate over network sockets.

Sockets offer two basic kinds of communication. TCP is connection-oriented: data is delivered as an ordered, reliable byte stream; lost packets are retransmitted. UDP is connectionless: each datagram is sent separately and delivery is not guaranteed; in return it carries less overhead. On the same machine, UNIX domain sockets (AF_UNIX) are faster, because they do not pass through the network stack; they are named by a path name in the file system. Docker, systemd, and the X/Wayland display servers communicate with processes over these sockets.

3.7Multitasking on mobile systems

On a desktop, an application left open keeps running even when the user switches to another window. On phones the situation is different. Memory is limited, swap space is either absent or small, and above all the battery is limited. An application that uses the processor continuously in the background can drain the battery within hours. Mobile operating systems therefore restrict background processes strictly.

iOS and iPadOS. The first iPhone software (2007) allowed only a single user application to run; everything other than the foreground application was closed. iOS 4 (2010) introduced limited multitasking. Even today only certain kinds of work can continue in the background: audio playback, location tracking, VoIP (voice calls over the Internet), and tasks scheduled with BGTaskScheduler. An application that uses none of these permissions is suspended shortly after it is moved to the background: the process stays in memory but is given no processor time. When memory is needed, the system can terminate suspended applications without warning; when the user returns, the application rebuilds its state.

Android. Android has allowed background processes from the start. Long-running work is carried out with the service component; a music player keeps playing thanks to its service even while its user interface is suspended. Since Android 8 (2017), however, there have been background restrictions. A long job must either run as a foreground service that shows the user a notification, or be split into WorkManager tasks that the system runs at a suitable moment.

foregroundthe activity the user is interacting withvisibleon screen but not in focusservicee.g. background synccachedbackground + empty processeswhen memory runs low, those at the bottom are killed first (lmkd)
Figure 3.34: The importance order of processes on Android: foreground, visible, service, and cached processes. When memory runs low, lmkd kills processes starting from the lowest group.

When memory is tight, Android decides which process to kill by an importance ranking (Figure 3.34). At the top is the foreground process with which the user is interacting. It is followed by visible processes, which are on screen but not in focus, and service processes that do work in the background. At the bottom are the cached processes. The “background” and “empty” processes mentioned separately in older documents are now gathered in this group. When memory runs low, lmkd (low memory killer daemon) kills processes starting from the bottom. Killing a cached process is invisible to the user; when the application is opened again, it is started from scratch.

Although the two systems take different approaches, the reason is the same: limited memory and battery. The assumption on the desktop that “a process ends of its own accord” does not hold on mobile. Mobile applications are written on the assumption that they can be suspended or terminated at any moment, and they save their state regularly.

3.8Summary

  • A process is an instance of a program in execution. A program is a passive file sitting on disk; a process is an active entity with an address space, a processor context (program counter, registers), and resources (open files, identifiers). Many processes can arise from the same program.
  • The address space of a process consists, from bottom to top, of the text, data, BSS, heap, and stack regions; at the very top is the kernel space, which user mode cannot access. The heap grows upward and the stack downward. Initialized global and static variables are in data, uninitialized ones in BSS, local variables on the stack, and memory allocated with malloc on the heap.
  • A single core switches rapidly among processes and creates pseudoparallelism; this is called multiprogramming. Concurrency is tasks progressing in the same interval, and parallelism is tasks running at the same instant; it requires several cores.
  • fork() creates a copy of the calling process; it returns the child’s PID to the parent, 0 to the child, and −1 to the parent on error. The copying is done lazily with copy-on-write. n consecutive unconditional forks produce 2n processes. Unwritten data in the stdio buffer is duplicated by fork.
  • The exec family replaces the process image with a new program; the PID, the parent, and the open file descriptors that were not closed are preserved. A successful exec does not return. All six functions end up in execve().
  • On every command the shell runs the fork → exec → wait loop. That fork and exec are separate lets the child prepare its own environment (redirection, directory, priority) before exec. open returns the lowest free descriptor number.
  • A process terminates voluntarily (exit) or involuntarily (fatal error, signal). Only the low 8 bits of the exit status reach the parent. SIGTERM can be caught; SIGKILL cannot.
  • A zombie is a finished process that has not been reaped; it consumes a PID. An orphan is a running process whose parent has died; init/systemd (or a subreaper) adopts it and reaps it when it ends. The remedy for accumulating zombies is wait/waitpid or a SIGCHLD handler.
  • The five-state model: New → Ready ⇄ Running → Waiting → Ready … → Terminated. There is no Waiting → Running transition; a process whose time slice expires returns to Ready. Linux merges ready and running into R and splits waiting into S and D.
  • The kernel tracks every process with a PCB; in Linux this structure is task_struct. The PCB carries process, memory, and file management information; the program counter and registers are the process’s context. Queues are linked lists of PCBs.
  • In the model of independent I/O waiting, CPU utilization is 1 − pn; each additional process gains less than the one before.
  • A context switch saves the old process’s context and loads the new one’s, and is pure overhead; its indirect cost (the cooling of the cache and the TLB) is often greater than its direct cost. In limited direct execution, the program runs on the processor at full speed; the timer interrupt returns control to the operating system.
  • IPC has two models. Shared memory is very fast and involves no kernel after setup, but leaves coordination to the processes. Message passing goes through the kernel on every message, the kernel provides the coordination, and it also works over a network. Blocking send and receive form a rendezvous.
  • A pipe is a one-way FIFO buffer in the kernel. Reading from an empty pipe blocks; when no open write end remains, read returns 0 (EOF). Unused ends must be closed. The shell builds pipelines with pipe, fork, dup2, and exec. A socket is an endpoint made of an IP address and a port.
  • Because of limited memory and battery, mobile systems suspend background processes and terminate them if necessary; Android does this with lmkd according to an importance ranking.
Table 3.17: The basic UNIX calls of the chapter.
CallWhat it doesReturn value
fork()creates a copy of the calling processthe child’s PID in the parent, 0 in the child, −1 on error
exec…()replaces the program in the processdoes not return on success; −1 on error
wait() / waitpid()waits for a child to finish and reaps itthe PID of the finished child; 0 with WNOHANG if none has finished
exit()flushes the buffers and terminates the processdoes not return
kill()sends a signal to a process0 on success, −1 on error
pipe()creates a pipe: fd[0] is the read end, fd[1] the write end0 on success, −1 on error
dup2(old, new)makes descriptor new a copy of oldnew

3.9Key terms

  • process
  • executable file
  • address space
  • program counter (PC)
  • register
  • thread
  • multiprogramming
  • concurrency
  • parallelism
  • parent / child process
  • copy-on-write (COW)
  • page fault
  • shell
  • file descriptor
  • system call
  • signal
  • zombie process
  • orphan process
  • process state
  • process control block (PCB)
  • ready queue
  • scheduler
  • dispatcher
  • preemptive / nonpreemptive scheduling
  • time slice (quantum)
  • CPU-bound / I/O-bound
  • context switch
  • interrupt
  • interrupt vector
  • trap
  • timer
  • user mode / kernel mode
  • interprocess communication (IPC)
  • shared memory
  • message passing
  • race condition
  • synchronization
  • synchronous / asynchronous communication
  • buffer
  • pipe
  • socket

3.10Test Yourself

  1. When the following fragment is run, how many lines of X are printed and how many processes are created in total? What does the process tree look like?

    if (fork() == 0)
        fork();
    printf("X\n");
    Answer

    At the start there is P0. The first fork creates P1. In P0 the return value is the child’s PID, that is, not 0; the condition is false and P0 goes straight to printf. In P1 the return is 0; the condition is true and P1 creates P2 with the second fork. P1 and P2 also reach printf. There are 3 processes in total (2 of them new) and 3 lines of X. The tree is a chain: P0 → P1 → P2.

  2. What does the program print? Is the order of the output certain?

    int x = 1;
    pid_t pid = fork();
    if (pid == 0) x = x * 3;
    else { wait(NULL); x = x + 4; }
    printf("%d\n", x);
    Answer

    The child computes x = 1 · 3 = 3 in its own copy and prints 3. The parent first waits for the child; then it computes x = 1 + 4 = 5 in its own copy and prints 5. Because the parent waits with wait for the child to finish before printing, the order is certain: first 3, then 5. The parent’s x is never 3, because after fork there are two separate x variables.

  3. The following program is run first in the terminal and then with ./prog > c.txt. What is seen in the two cases? Why?

    printf("first\n");
    execlp("echo", "echo", "then", NULL);
    printf("error\n");
    Answer

    In the terminal, stdout is line-buffered; "first\n" is written at once because of the newline. Then exec succeeds and echo prints then. Two lines are seen on the screen: first, then. With redirection to a file, stdout is fully buffered; "first\n" waits in the buffer in the process’s memory. When exec discards the address space, the buffer is lost too. c.txt contains only then. error is not printed in either case, because exec succeeds. The remedy is to call fflush(stdout) before exec.

  4. Processes spend half of their time waiting for I/O. How many processes must be in memory for CPU utilization to be at least 99%?

    Answer

    We need p = 0.5 and 1 − 0.5n ≥ 0.99; that is, 0.5n ≤ 0.01. 0.56 = 0.015625 → utilization 98.44%; not enough. 0.57 = 0.0078125 → utilization 99.22%; enough. With logarithms, n ≥ ln 0.01 / ln 0.5 ≈ 6.64; rounded up, 7 processes are needed.

  5. A context switch takes 0.02 ms. There are 4 CPU-bound processes running in turn in the ready queue, and the time slice is 1 ms. What percentage of processor time goes to switches? At most how long does a process wait between two of its slices?

    Answer

    The overhead fraction is 0.02 / (1 + 0.02) = 0.02 / 1.02 ≈ 1.96%. When a process’s slice ends, 4 switches and the slices of the other 3 processes pass: 4 · 0.02 + 3 · 1 = 3.08 ms.

  6. In the ps output there are three processes whose STAT column is S, D, and Z. Which one can be terminated at once with Ctrl+C, which does not respond even to kill -9, and which is pointless to kill? How is the last one cleaned up?

    Answer

    S is in interruptible sleep; a signal wakes it and it terminates on SIGINT. D is in uninterruptible sleep, usually waiting for a disk operation; even SIGKILL is not delivered until the operation finishes. Z is a zombie, that is, already finished; there is nothing left to kill. The zombie is reaped by its parent with wait. If the parent does not do this, the parent is terminated; the zombie passes to init, and init reaps it.

  7. A child process exits with exit(256) in one run and with exit(-1) in another. Which values does the parent read with WEXITSTATUS(st)? Does the shell count the command as successful in the first case?

    Answer

    Only the low 8 bits reach the parent. 256 mod 256 = 0, so the parent reads 0. The low 8 bits of −1 are 1111 1111; the parent reads 255. In the first case the shell sees 0 and counts the command as successful, although the program meant to report an error. Portable programs therefore use only the range 0–255.

  8. Before exec, a child process runs the following two lines. What is the value of fd? If execlp("sort", "sort", NULL) is then called, where does sort read its data from? Which shell notation does this correspond to?

    close(0);
    int fd = open("input.txt", O_RDONLY);
    Answer

    close(0) closes standard input and number 0 becomes free. Because open returns the lowest free number, fd = 0. exec preserves the file descriptor table; sort reads from standard input, that is, from number 0, which is now input.txt. This corresponds to the shell notation sort < input.txt.

  9. A server creates a child with fork for every request but never calls wait. 50 requests arrive per second and every child finishes its work immediately. At most 32,000 processes can exist in the system at the same time, and there are 500 processes when the server starts. After how long does fork begin to fail? What is the remedy?

    Answer

    Each child becomes a zombie when it finishes and keeps holding its PID. The free room is 32,000 − 500 = 31,500 processes. Because 50 zombies accumulate per second, no new process can be created after 31,500 / 50 = 630 seconds, that is, 10.5 minutes. The remedy is to reap the finished children in the SIGCHLD handler with a waitpid(-1, NULL, WNOHANG) loop.

3.11Further reading

  • R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters “Processes,” “Process API,” and “Limited Direct Execution”: they present the process abstraction, the fork/exec/wait pattern, and the regaining of control through the timer interrupt in short chapters. The book is online and free.
  • A. Silberschatz, P. B. Galvin, and G. Gagne, Operating System Concepts (10th edition, 2018), Chapter 3: treats process states, the PCB, and the IPC models more broadly, with Windows and Android examples.
  • A. S. Tanenbaum and H. Bos, Modern Operating Systems (4th edition), Section 2.1: gives a detailed account of the process model, the fields of the process table, interrupt handling, and the multiprogramming model.
  • M. Kerrisk, The Linux Programming Interface (2010), Chapters 24–28 and 44: a reference for fork, exec, wait, process termination, and pipes. It treats in detail Linux-specific pitfalls such as buffers, signals, and zombies.

3.12References

  1. R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, Arpaci-Dusseau Books, pages.cs.wisc.edu/~remzi/OSTEP.
  2. Chromium Projects, “Multi-process Architecture” and “Site Isolation” documents.
  3. Android Developers, “Processes and app lifecycle”.
  4. M. Kerrisk, The Linux Programming Interface, No Starch Press, 2010.
  5. Linux manual pages: fork(2), execve(2), wait(2), pipe(7), signal(7), shm_overview(7).
  6. A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th edition, Wiley, 2018.
  7. A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th edition, Pearson, 2014 (5th edition 2023).

Related pages: Chapter 3 slides · © Sercan Külcü. All rights reserved.