Chapter 06 of 38

Process Control Block & Context Switching

Imagine you are reading a novel and your phone rings. Before you put the book down, you slip a bookmark in, and maybe note "Chapter 7, the part where the detective finds the letter". When you come back, you open the book at that page and carry on as if nothing happened.

An operating system does the same thing thousands of times every second. A single CPU core can run only one process at a time, yet your laptop seems to run a browser, a music player and a code editor together. The OS achieves this by constantly pausing one process and resuming another. To pause a process safely, it needs a "bookmark" that records exactly where the process was and what it was doing.

That bookmark is the Process Control Block (PCB), and the act of pausing one process and resuming another is called a context switch.

A Process Control Block (PCB) is the data structure the kernel keeps for every process. It stores everything the OS needs to know to manage that process and to stop and restart it later.

In the previous chapter, Processes & Process States, we saw that a process moves between states such as New, Ready, Running, Waiting and Terminated. In this chapter we look at how the OS keeps track of each process and what actually happens when the CPU moves from one process to another.


What Is Stored in a PCB?

A PCB is sometimes called a task control block. Its exact layout differs from one OS to another, but every textbook PCB contains the same groups of information:

┌─────────────────────────────────┐
│ Process ID (PID), parent PID     │  ← identification
├─────────────────────────────────┤
│ Process state                    │  ← New / Ready / Running / Waiting ...
├─────────────────────────────────┤
│ Program counter                  │  ← address of next instruction
├─────────────────────────────────┤
│ CPU registers                    │  ← general registers, stack pointer,
│                                  │    flags / status word
├─────────────────────────────────┤
│ CPU scheduling information       │  ← priority, pointers to queues
├─────────────────────────────────┤
│ Memory-management information    │  ← page table pointer, base/limit
├─────────────────────────────────┤
│ Accounting information           │  ← CPU time used, start time, limits
├─────────────────────────────────┤
│ I/O status information           │  ← open files, allocated devices
└─────────────────────────────────┘

Field

What It Holds

Why the OS Needs It

Process ID (PID)

A unique number for the process, plus the PID of its parent

To identify the process in system calls such as kill or wait

Process state

Ready, Running, Waiting, etc.

So the scheduler knows whether the process can be picked

Program counter (PC)

Address of the next instruction to execute

To resume the process at exactly the right instruction

CPU registers

Values of general-purpose registers, stack pointer, status/flags register

Half-finished calculations live in registers; losing them would corrupt the program

Scheduling information

Priority, pointers into scheduling queues, other scheduler parameters

To decide which process runs next

Memory-management information

Page table address (or base and limit registers, or segment table)

So the process sees its own memory and nobody else's

Accounting information

CPU time used, time limits, start time

For tools like top, for billing, and for enforcing limits

I/O status information

List of open files, I/O devices allocated to the process

To read/write the right files and release them when the process exits

Notice the pattern: the first few fields describe where the process is in its execution (PC, registers), and the rest describe what the process owns (memory, files) and how the OS should treat it (priority, accounting).

Where Does the PCB Live?

PCBs are stored in kernel memory. A user program cannot read or change its own PCB directly. If it could, a program could simply raise its own priority or point its page table at another program's memory. The kernel only exposes selected, read-only views of this information through system calls and special files.

The kernel keeps all PCBs in a process table (often a list or a tree), so it can find a process quickly by its PID.


The PCB in a Real OS: Linux's task_struct

In Linux, the PCB is a large C structure called struct task_struct, defined in the kernel source file include/linux/sched.h. It has hundreds of fields: the PID, the state, scheduling data, a pointer to the memory descriptor (mm), the open-file table (files), signal handlers, credentials, parent and child links, and much more.

You cannot read task_struct directly, but Linux shows a summary of it in /proc/<pid>/status. Here are selected lines from running cat /proc/self/status on Ubuntu (WSL2, kernel 6.18). The word self means "the process reading this file", which here is cat itself:

Name:	cat
State:	R (running)
Tgid:	1506
Pid:	1506
PPid:	1503
Uid:	1000	1000	1000	1000
FDSize:	64
VmSize:	   16244 kB
VmRSS:	    7492 kB
Threads:	1
Cpus_allowed_list:	0-11
voluntary_ctxt_switches:	0
nonvoluntary_ctxt_switches:	1

You can match many of these lines with the textbook PCB fields:

  • Pid, PPid → identification

  • State → process state

  • Uid → who owns the process (used for protection)

  • FDSize → size of the open-file table (I/O status)

  • VmSize, VmRSS → memory-management information

  • Cpus_allowed_list → scheduling information (which cores it may run on)

  • voluntary_ctxt_switches, nonvoluntary_ctxt_switches → accounting information about context switches, which we will use later in this chapter

The saved registers and program counter are not shown here. On Linux, when a process enters the kernel, its user-mode registers are saved on that process's kernel stack, and some extra CPU state is kept in a per-task structure called thread_struct. Both are reachable from the task_struct, so conceptually they are still "part of the PCB".


PCBs and Scheduling Queues

The OS does not move programs around in memory when they change state. It moves PCBs (really, pointers to PCBs) between queues.

Ready queue:   head → [PCB P3] → [PCB P7] → [PCB P1] → NULL

Disk I/O queue: head → [PCB P2] → [PCB P5] → NULL

Keyboard queue: head → [PCB P4] → NULL

Running on CPU: P6

When P6 asks to read from the disk, the kernel changes the state in P6's PCB to Waiting and links it into the disk queue. When the disk finishes, P6's PCB is moved to the ready queue. The program's code and data never move; only a few pointers change. This is one reason state changes are cheap.


What Is a Context Switch?

The context of a process is everything the CPU needs to continue running it: the program counter, the register values, and the memory-mapping information. All of this is saved in (or reachable from) the PCB.

A context switch is the act of saving the context of the currently running process into its PCB and loading the saved context of another process from its PCB, so that the CPU continues executing the second process.

Here is the classic picture of two processes sharing one CPU:

   Process P0                Operating System               Process P1

   executing
      │
      │  interrupt or system call
      └──────────────────────▶ save state into PCB0
                               ...
                               reload state from PCB1 ──────────▶ executing
                                                                      │
                                                                      │
   (idle: P0 is                                                       │
    ready or waiting)          interrupt or system call               │
                               save state into PCB1  ◀────────────────┘
                               ...
   executing ◀──────────────── reload state from PCB0
                                                          (idle: P1 is
                                                           ready or waiting)

While the OS is doing the saving and loading, neither P0 nor P1 is making progress. That time is pure overhead.


When Does a Context Switch Happen?

A context switch always starts with the CPU entering the kernel. The common triggers are:

  1. Timer interrupt: the running process has used up its time slice. The scheduler takes the CPU away and gives it to another ready process. This is an involuntary (preemptive) switch.

  2. Blocking system call: the process asks for something that is not ready yet, such as reading from disk, waiting for a key press, sleep(), or waiting for a lock. It cannot continue, so it gives up the CPU. This is a voluntary switch.

  3. A higher-priority process becomes ready: for example, an I/O completion wakes up an important process, and the scheduler decides it should run now.

  4. Process termination: the process calls exit(), so the CPU must be given to someone else.

Not every interrupt causes a context switch. If a network card interrupts, the kernel may handle the interrupt and then return to the same process. A context switch happens only when the scheduler decides that a different process should run.


Steps of a Context Switch

Suppose process A is running and a timer interrupt arrives. The scheduler decides to run process B.

  1. Enter the kernel. The hardware switches the CPU to kernel mode and saves a minimal amount of A's state (such as the program counter and flags) so the kernel can run.

  2. Save A's context. The kernel saves A's remaining registers into A's PCB (or the kernel stack it points to).

  3. Update A's PCB. A's state changes from Running to Ready (timer) or Waiting (blocking call). Its PCB is placed in the matching queue. Accounting fields such as CPU time used are updated.

  4. Run the scheduler. The scheduler picks the next process, B, from the ready queue.

  5. Switch the address space. The kernel loads B's memory-management information, for example the page table base register (CR3 on x86). From now on, memory addresses refer to B's memory.

  6. Restore B's context. B's saved registers are loaded from its PCB, and B's state is set to Running.

  7. Return to user mode. The CPU jumps to B's saved program counter. B continues exactly where it stopped, unaware that it was ever paused.

The small piece of kernel code that does steps 5 to 7 (giving control of the CPU to the chosen process) is called the dispatcher. We will meet it again in CPU Scheduling Basics.


Mode Switch vs Context Switch

Students often mix these up, and it is a favourite interview question.

A mode switch is a change of the CPU's privilege level, from user mode to kernel mode or back. Every system call causes a mode switch. But after a simple system call such as getpid(), the kernel returns to the same process, so no context switch happens.

Mode Switch

Context Switch

User mode ↔ kernel mode

Process A → process B

Same process continues afterwards

A different process continues afterwards

Happens on every system call and interrupt

Happens only when the scheduler picks a different process

No change of address space

Address space usually changes (different page table)

Relatively cheap

More expensive (save/restore + cache and TLB effects)

Every context switch includes at least one mode switch (you must be in the kernel to switch processes), but most mode switches are not context switches.


Why Context Switching Is Pure Overhead

During a context switch the CPU does no useful work for any user program. The cost has two parts.

Direct Cost

  • Saving and restoring registers

  • Running the scheduler code to choose the next process

  • Switching the page table

Indirect Cost (Often Bigger)

  • Cache pollution: the CPU caches are full of A's data. B starts with "cold" caches and suffers many cache misses at first.

  • TLB misses: the TLB caches A's address translations. After switching page tables, those entries are useless for B. Older CPUs flushed the entire TLB on every switch. Modern CPUs tag TLB entries with an address-space identifier (called ASID, or PCID on x86) so entries can survive a switch, which reduces this cost. You will learn about the TLB in Page Tables & TLB.

Switching between two threads of the same process is cheaper than switching between two processes, because the threads share one address space, so no page-table switch is needed and the TLB stays useful. We will see why in Threads & Multithreading.

How Much Does It Cost? Let's Measure

A classic way to measure this is a "ping-pong" test: two processes pinned to the same CPU core send one byte back and forth through pipes. Each process must block and wait for the other, so every message forces a context switch. (Pipes are explained in Inter-Process Communication, and fork() in Process Creation (fork & exec); for now, just think of them as "create a second process" and "a channel between them".)

#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#define ROUNDS 200000

int main(void) {
    int p2c[2], c2p[2];
    if (pipe(p2c) == -1 || pipe(c2p) == -1) { perror("pipe"); return 1; }

    /* Pin to CPU 0 so parent and child must take turns on ONE core */
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(0, &set);
    sched_setaffinity(0, sizeof set, &set);   /* inherited by the child */

    char b = 'x';
    pid_t pid = fork();
    if (pid == 0) {                           /* child: echo every byte back */
        for (int i = 0; i < ROUNDS; i++) {
            read(p2c[0], &b, 1);
            write(c2p[1], &b, 1);
        }
        _exit(0);
    }

    struct timespec s, e;
    clock_gettime(CLOCK_MONOTONIC, &s);
    for (int i = 0; i < ROUNDS; i++) {        /* parent: send, wait for echo */
        write(p2c[1], &b, 1);
        read(c2p[0], &b, 1);
    }
    clock_gettime(CLOCK_MONOTONIC, &e);
    waitpid(pid, NULL, 0);

    double ns = (e.tv_sec - s.tv_sec) * 1e9 + (e.tv_nsec - s.tv_nsec);
    /* each round trip = 2 context switches (parent->child, child->parent) */
    printf("Round trips: %d\n", ROUNDS);
    printf("Time per switch (incl. pipe read/write): %.2f microseconds\n",
           ns / (2.0 * ROUNDS) / 1000.0);
    return 0;
}

Compile and run on Linux:

gcc -std=c17 -Wall -Wextra pingpong.c -o pingpong
./pingpong

Output on my machine (Ubuntu on WSL2, GCC 15):

Round trips: 200000
Time per switch (incl. pipe read/write): 0.90 microseconds

So one switch, including the small pipe read and write, took roughly one microsecond. Your number will be different: it depends on the CPU, the kernel version, security mitigations, and whether you are in a virtual machine. The important lesson is the order of magnitude: microseconds, which is thousands of instructions' worth of time.


Watching Context Switches Happen

The kernel counts context switches for every process. The getrusage() system call returns two counters:

  • ru_nvcsw: voluntary context switches (the process blocked, e.g. on I/O or sleep)

  • ru_nivcsw: involuntary context switches (the kernel preempted the process, e.g. its time slice ended or a higher-priority task needed the CPU)

#define _GNU_SOURCE
#include <stdio.h>
#include <sys/resource.h>
#include <unistd.h>
#include <time.h>

static void show(const char *when) {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    printf("%-22s voluntary=%ld  involuntary=%ld\n",
           when, ru.ru_nvcsw, ru.ru_nivcsw);
}

int main(void) {
    show("At start:");

    /* 1. Sleep 5 times: each sleep gives up the CPU voluntarily */
    for (int i = 0; i < 5; i++)
        usleep(1000);              /* 1 ms */
    show("After 5 sleeps:");

    /* 2. Burn CPU for about 2 seconds: the scheduler may preempt us */
    struct timespec s, n;
    clock_gettime(CLOCK_MONOTONIC, &s);
    volatile unsigned long x = 0;
    do {
        for (int i = 0; i < 1000000; i++) x += i;
        clock_gettime(CLOCK_MONOTONIC, &n);
    } while (n.tv_sec - s.tv_sec < 2);
    show("After 2 s of CPU work:");
    return 0;
}

Output (one run):

At start:              voluntary=0  involuntary=0
After 5 sleeps:        voluntary=5  involuntary=0
After 2 s of CPU work: voluntary=5  involuntary=4

What does this tell us?

  • Each usleep() blocks the process, so it gives up the CPU voluntarily: exactly 5 voluntary switches for 5 sleeps.

  • The busy loop never blocks, so the voluntary count does not change. But the scheduler still took the CPU away a few times to let other tasks run: these are involuntary switches.

  • The involuntary number varies from run to run, because it depends on what else the machine is doing. Do not expect the same value on your computer. Even the starting values may not be 0 on your machine: for example, if the program file is on a slow or network-mounted disk, loading it can block a few times before main() even starts.

An I/O-heavy program (like a web server) usually shows many voluntary switches. A CPU-heavy program (like video encoding) shows mostly involuntary ones. This difference becomes important in CPU Scheduling Basics.


Worked Example: Context Switch Overhead

Suppose a context switch takes s = 1 ms (exaggerated, to keep the numbers simple), and the OS lets each process run for a time slice of q ms before switching. Out of every q + s ms, only q ms is useful work:

Useful fraction  = q / (q + s)
Overhead         = s / (q + s)

Time slice q

Useful CPU time

Wasted on switching

1 ms

50.00%

50.00%

4 ms

80.00%

20.00%

10 ms

90.91%

9.09%

100 ms

99.01%

0.99%

Very short time slices waste a lot of time on switching. Very long slices waste little time but make the system feel sluggish, because a process may wait a long time for its turn. Choosing the slice is a trade-off we will study in Round Robin Scheduling.

A Small Exam-Style Question

Three processes, each needing 10 ms of CPU time, all start at time 0. The OS gives the CPU to them in turn (P1, P2, P3, P1, P2, P3, ...) with a time slice of 2 ms. Every switch from one process to another costs 0.5 ms. How long until all three finish, and what fraction of that time is useful?

  • Each process needs 10 / 2 = 5 slices, so there are 3 × 5 = 15 slices.

  • Every slice is followed by a different process, so there is a switch between every pair of consecutive slices: 15 − 1 = 14 switches (no switch is counted after the very last slice).

  • Total time = 30 ms of work + 14 × 0.5 ms = 30 + 7 = 37 ms.

  • Useful fraction = 30 / 37 ≈ 81.08%.

Always read the question carefully: some exams also count a switch at the start (loading the first process) or at the end. State your assumption in the answer.


Common Mistakes

  • "The PCB stores the program's code." No. The PCB stores information about the process (state, registers, pointers to memory). The code and data stay in the process's memory; the PCB only points to them through the memory-management information.

  • "Every system call is a context switch." No. A system call is a mode switch. A context switch happens only if the kernel decides to run a different process, for example because the call blocks.

  • "Context switching is done by the process itself." No. It is always done by the kernel. Even a voluntary switch (e.g. sleep()) only asks the kernel to run someone else.

  • "More context switches means more multitasking, so it's better." Each switch is overhead. Too many switches (e.g. a tiny time slice) can make the whole system slower.

  • Forgetting the indirect cost. Saving registers is quick. Refilling caches and the TLB afterwards is often the bigger cost.


Interview Questions

What is a PCB? Name its main fields.

A Process Control Block is the kernel data structure for one process. It holds the PID, process state, program counter, CPU registers, scheduling information (priority, queue pointers), memory-management information (page table pointer), accounting information (CPU time used) and I/O status (open files, devices).

Why can't a user program modify its own PCB?

The PCB lives in kernel memory. If a program could edit it, it could raise its own priority, change its user ID, or point its page table at other processes' memory, breaking both fairness and protection.

What exactly is saved during a context switch?

The program counter, the general-purpose registers, the stack pointer, the status/flags register and the memory-mapping information (such as the page table base). Together these let the process resume exactly where it stopped.

What is the difference between a mode switch and a context switch?

A mode switch changes the CPU privilege level (user ↔ kernel) and the same process continues. A context switch replaces the running process with another one, saving and restoring the full context. Every system call causes a mode switch; only some cause a context switch.

Why is a thread switch cheaper than a process switch?

Threads of the same process share one address space, so the kernel does not need to switch page tables, and the TLB and caches still hold useful data. Only the per-thread registers and stack pointer change.

What is the difference between voluntary and involuntary context switches?

A voluntary switch happens when the process blocks (I/O, sleep, waiting for a lock). An involuntary switch happens when the kernel preempts a process that could have continued, for example when its time slice expires or a higher-priority process becomes ready.

What is the PCB called in Linux?

struct task_struct, defined in include/linux/sched.h. Parts of it can be viewed in /proc/<pid>/status.


Summary

  • The PCB is the kernel's record of a process: identity, state, program counter, registers, scheduling, memory, accounting and I/O information.

  • PCBs live in kernel memory and are linked into queues (ready queue, device queues). Changing a process's state means moving its PCB between queues.

  • In Linux, the PCB is task_struct; /proc/<pid>/status shows a summary.

  • A context switch saves the running process's context into its PCB and restores another process's context from its PCB.

  • Triggers: timer interrupt (involuntary), blocking system call (voluntary), higher-priority process waking up, process exit.

  • A mode switch (user ↔ kernel) is not the same as a context switch.

  • Context switches are pure overhead: direct cost (save/restore, scheduler) plus indirect cost (cold caches, TLB misses). On modern hardware a switch costs on the order of a microsecond.

The PCB is the bookmark; the context switch is putting one book down and picking another one up.