What the kernel gives a running program
A process is the unit of isolation. It owns:
- a virtual address space: code, global data, heap, memory mappings and one stack per thread;
- a file descriptor table: open files, sockets, pipes;
- credentials (user and group ids), signal handlers, resource limits and a current directory;
- one or more threads.
A thread is the unit of execution. It owns only a register set (including the program counter and stack pointer), its own stack, thread-local storage, a signal mask and a scheduling state. Everything else is shared with the other threads of its process.
| Separate processes | Threads of one process | |
|---|---|---|
| Memory | Isolated; share only via explicit shared memory, pipes, sockets | Shared: a pointer means the same thing in every thread |
| A crash | Kills one process | Kills every thread in the process |
| Communication | IPC (copy or shared-memory mapping) | Ordinary loads and stores, plus synchronisation |
| Switch between them | Changes page tables | Keeps page tables |
On Linux both are tasks created by the clone system call; the flags decide what is shared. fork shares nothing (memory is copied lazily), while pthread_create passes CLONE_VM | CLONE_FILES | CLONE_SIGHAND | ... so the new task shares the address space and descriptors. Each task has a kernel thread id; the process id is the id of its first thread.
User mode, kernel mode and system calls
The CPU runs ordinary code in an unprivileged mode (user mode: ring 3 on x86-64, EL0 on ARM). Privileged work, such as touching device registers, changing page tables or disabling interrupts, is allowed only in kernel mode (ring 0, EL1). A program asks the kernel for a service with a system call: it puts a call number and arguments in registers and executes a trap instruction (syscall on x86-64, svc on ARM). The CPU switches mode, jumps to the kernel's entry point, the kernel does the work and returns.
A system call is not a context switch: the same thread keeps running, it just crosses into the kernel and back. Its cost is the mode switch, register saving, security mitigations on entry and exit, and the work itself. For a trivial call that is on the order of 100 ns to 1 µs; one run of a loop of a million getppid() calls on an Apple-silicon laptop measured about 140 to 160 ns per call. Expensive calls (write to a socket, mmap) cost microseconds.
Some calls avoid the trap entirely. On Linux, clock_gettime and gettimeofday are served from the vDSO, a small library the kernel maps into every process, so reading the clock costs tens of nanoseconds. That is why latency-sensitive code timestamps freely but avoids other system calls on the hot path.
Things that always enter the kernel: file and socket I/O through the normal stack, mmap/munmap, blocking on a futex (the kernel half of a contended mutex or condition variable), sleeping, creating threads and processes. A large malloc may call mmap; a small one usually does not.
fork, exec and wait
The Unix way to run a program is two steps:
fork()creates a child that is a copy of the caller. It returns twice: the child's pid in the parent, and 0 in the child. The copy is lazy: parent and child share the physical pages, marked read-only, and a page is duplicated only when one side writes to it (copy-on-write). Forking a process with 10 GB of heap is therefore fast; it copies page tables, not data.execve()(or a wrapper such asexecvp) replaces the calling process's program with a new one. The pid stays the same, and so do open file descriptors unless they were opened withO_CLOEXEC. It returns only on failure.
The parent calls waitpid() to collect the child's exit status. A child that has exited but not yet been waited for is a zombie: it holds only a process-table entry. A child whose parent exits first is an orphan and is re-parented to init (or a designated subreaper), which reaps it.
#include <cstdio>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
char* argv[] = {(char*)"echo", (char*)"hello from exec", nullptr};
execvp("echo", argv); // only returns on failure
std::perror("execvp");
_exit(127);
}
int status = 0;
waitpid(pid, &status, 0);
if (WIFEXITED(status))
std::printf("child %d exited with %d\n", (int)pid, WEXITSTATUS(status));
}
This prints hello from exec and then child <pid> exited with 0. The shell does exactly this for every command you type, with redirections done by dup2 between the fork and the exec.
Worked example
process memory versus thread memory
What does this program print, and why? (Compiled with c++ -std=c++20 -O2.)
#include <cstdio>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
int counter = 0;
int main() {
pid_t pid = fork();
if (pid == 0) { // child: a copy of the parent's address space
counter = 100;
std::printf("child sees %d\n", counter);
std::fflush(stdout); // _exit skips stdio flushing
_exit(0);
}
waitpid(pid, nullptr, 0);
std::printf("parent sees %d after fork\n", counter);
std::thread t([] { counter = 100; }); // a thread shares the address space
t.join();
std::printf("parent sees %d after thread\n", counter);
}
Show solutionHide solution
child sees 100
parent sees 0 after fork
parent sees 100 after thread
- After
fork,counterexists at the same virtual address in both processes, but the child's write triggers copy-on-write: the child gets its own physical copy of that page. The parent's page is untouched, so it still reads 0. - The thread runs in the parent's address space, so its store is visible to the parent after
join(which also provides the needed happens-before ordering). - The
fflushmatters.printfwrites into a user-space buffer, and_exitends the process without flushing it. When stdout is a terminal the buffer is flushed at each newline, but when stdout is a pipe or file it is fully buffered, and without thefflushthe child's line silently disappears. The mirror-image bug: data buffered before aforkis printed twice, once by each process.
Context switches and what they cost
A context switch is the kernel taking one thread off a CPU and putting another on. It happens when a thread blocks (a voluntary switch: waiting on I/O, a futex or a sleep) or when the scheduler preempts it (an involuntary switch: its time slice ran out or a higher-priority task woke). The kernel saves the outgoing thread's registers, picks the next task and restores its registers. If the next task belongs to a different process, it also switches page tables; with tagged TLBs (PCID on x86, ASID on ARM) the old translations need not be flushed, but they compete for space.
Costs, as orders of magnitude:
- Direct cost: about 1 to a few µs for the switch itself, including the system call or interrupt that triggered it.
- Indirect cost: the new thread starts with caches, TLB and branch predictors full of someone else's state. Refilling them can slow the next tens of microseconds, and this often exceeds the direct cost.
- Wake-up latency: a blocked thread that is woken must wait for the scheduler to run it, possibly after the CPU leaves a sleep state. Signalling a sleeping thread and getting a reply typically takes several to tens of µs, against roughly 100 ns for two spinning threads (the Scheduling lesson measures this).
A thread switch within one process is cheaper than a process switch, mainly because the address space and its TLB entries stay valid. On Linux you can see the counts in /proc/<pid>/status as voluntary_ctxt_switches and nonvoluntary_ctxt_switches.
Worked example
a system call per message
A feed handler processes bursts of 1,000,000 messages per second on one core, and it logs a 100-byte line per message with a write() system call costing 0.5 µs. How much of the core does logging use? Redesign it.
Show solutionHide solution
Kernel time per second is s, so half the core goes to logging, and each message pays 0.5 µs of latency against a per-message budget of 1 µs.
Redesign: the hot thread copies the line into a pre-allocated in-memory ring buffer (tens of nanoseconds, no system call), and a background thread on another core drains it with one write() per 64 KiB block. A 64 KiB block holds lines, so the drain thread makes about calls per second, costing ms of kernel time per second, off the hot path. Better still, log binary records and format them later.
The interview point: say where the kernel is entered, put a number on it, and move it off the critical path by batching or by handing it to another thread.
Knowledge check
A parent process holds a 2 GB array, forks, and the child changes one element and exits. Roughly how much memory did the fork and the write copy?
Knowledge check
Which statement about system calls is correct?
Knowledge check
Why is switching between two threads of one process usually cheaper than switching between two processes?
Key takeaways
- A process owns an address space and resources; a thread is an execution context inside one. On Linux both are tasks made by
clone. forkcopies lazily (copy-on-write) and returns twice;execreplaces the program and keeps the pid and descriptors;waitpidreaps the child.- A system call is a mode switch of the same thread, roughly 100 ns to 1 µs for a trivial one; the vDSO serves the clock without a trap.
- A context switch costs microseconds directly and more through cold caches; wake-ups from blocking cost several to tens of microseconds.
- On a hot path, count every kernel entry and move it off by batching or handing work to another thread.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).