Lesson 1 of 26 · 12 min read
What an operating system actually does
See why a program that loops and prints relies on virtualization, concurrency, and persistence before a single character reaches your screen.

Course syllabus · lesson 1 of 26
In this lesson
OSTEP Chapter 2 crux — How to virtualize resources. How does the operating system turn finite physical resources into abstractions that programs can use independently, and what hardware support lets it do so efficiently? The chapter asks two companion questions: how to build correct concurrent programs and how to store data persistently despite failures.
Consider two copies of a program that increment a counter once per second. Each copy experiences a continuous execution history, has its own counter, and can print to a shared terminal. Underneath, both may use the same CPU registers at different times, refer to the same numerical address in different address spaces, and send bytes to a device the kernel manages. You can reason about each sharing problem by identifying the resource, who owns the state, and when that state changes.
Follow a command from shell to disk
Step 1 of 3
Start a program
The shell starts a process. The OS gives it a virtual address space and schedules its instructions on the CPU.
A CPU shared in time
On one core, at most one thread runs at a time in our model. A scheduler can nevertheless let four continuously ready jobs make progress. Say the quantum is 5 ms, jobs A through D start together, and context switches take zero time. A runs from 0 to 5 ms, B from 5 to 10, C from 10 to 15, and D from 15 to 20. At 20 ms A resumes with the program counter and register values it had at 5 ms. In that 20 ms interval each gets 5 ms, or 25 percent of the processor. The work proceeds concurrently over the interval, although no two jobs use the core in parallel.
Now let B block for input after consuming 1 ms of its slice. C can start at 6 ms because B has no instructions it can usefully execute until input arrives. B still owns its saved execution state while asleep. When input arrives, the kernel marks B eligible to run and the scheduler chooses when to dispatch it. The virtual CPU is thus a promise that execution can resume with the right state, subject to scheduling and resource availability.
The kernel needs two capabilities to make that possible. It needs hardware to hand control back through interrupts or other protected entries and code to save and restore execution state. It also needs a rule for choosing a ready job. The former is mechanism. A fixed rotation among ready jobs or preference for a job that has just received input is policy. A bad policy can leave an editor sluggish even when every register restores correctly. A bad mechanism can corrupt a job's execution even when the scheduler chooses exactly the right job.
Memory shared in space
A pointer printed by a program is a virtual address. The hardware's memory management unit translates it using mappings selected for the current address space. For a worked example, take a 4 KiB page. Virtual address 0x601010 names virtual page 0x601 with offset 0x010. If A maps page 0x601 to frame 0x12, the physical byte is at 0x12010. If B maps that page to frame 0x39, the physical byte is at 0x39010. Both translations preserve the low 12 bits. Loads and stores affect different bytes even though the instructions use the same virtual address.
A mapping also carries access permissions. A store to a valid writable mapping can proceed in user mode, while a store through a read-only mapping faults. The kernel can resolve some faults, such as by allocating a zero-filled frame for a valid anonymous page on first use. An access outside any valid region may instead end the process. Explicit sharing is possible too. The kernel can map the same physical frame into two address spaces, potentially at different virtual addresses. Isolation depends on how frames are mapped and protected.
Here is a small experiment. The two launches can show different pointers because the loader and allocator can choose different addresses. Predict the count for each PID.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int *p = malloc(sizeof *p);
if (p == NULL)
return EXIT_FAILURE;
*p = 0;
for (int i = 0; i < 3; ++i) {
++*p;
printf("pid=%ld address=%p value=%d\n", (long)getpid(), (void *)p, *p);
fflush(stdout);
sleep(1);
}
free(p);
return EXIT_SUCCESS;
}
cc -Wall -Wextra -o counter counter.c
./counter &
./counter &
wait
The allocation uses the pointed-to type for its size. The null check must precede the first store, and initialization must precede the first increment. Allocation supplies storage whose initial value the program cannot assume. The cast to void * matches the contract of %p. fflush sends pending library output toward the kernel even when standard output is redirected and buffered. sleep lets the process block, giving the other copy opportunities to run. Moving wait between the two launches would serialize them and hide the interleaving. Regardless of which PID prints first, each successful run prints 1, 2, and 3 in its own order.
The sleep itself requires coordination. The kernel can record when the process next becomes eligible and remove it from the set of runnable work. After the interval elapses, a timer event can make it runnable again. A one-second sleep does not reserve the core at the one-second mark. If the system is busy, the next line can appear later. The elapsed time printed by a user-facing tool would include that scheduling delay even though the process consumes little processor time.
Concurrency and the missing increment
Give one process two threads that share a counter. Both expect their increments to count. At the machine-operation level, imagine each increment as a load into a register, an add, and a store. Start at 41. Thread A loads 41 and computes 42. Before A stores, B loads 41, computes 42, and stores it. A then stores its own 42. Two increments have run and the final value is 42 instead of 43. This can happen by interleaving on one core or by parallel execution on two cores.
That trace illustrates the lost-update mechanism. In C, concurrent unsynchronized accesses to an ordinary integer, with at least one writer, form a data race and yield undefined behavior. The compiler need never emit the literal load/add/store loop we used on paper. A larger iteration count can make a problem easier to observe on a particular build, but neither a small count nor an observed correct result establishes correctness.
For one counter, a C atomic read-modify-write such as atomic_fetch_add can make the increment indivisible with respect to other atomic operations on the object. To keep a counter and another field consistent as a pair, a mutex can protect the entire update. Place the read, calculation, and write inside the same critical section. Taking the mutex only for the final store allows both threads to calculate from the same stale value. Joining both threads before printing the final count establishes that they have finished. Mutual exclusion or an atomic operation ensures that updates are performed correctly while they run.
Persistence and the path of a write
Consider a program that creates note.txt and writes a short message. It passes a pathname to open. The kernel resolves the directories, checks permissions, and returns a descriptor. The descriptor is an index in the process's table. Its entry refers to an open file description that holds the current offset and status flags. A file system object, often represented by an inode, records information such as file size and how to locate data. A directory entry associates the name note.txt with that object. Moving the descriptor, updating the offset, and editing the directory are operations on different state.
On a buffered path, write can copy user bytes into cached pages, mark them dirty, and report success before the device has persisted them. A short write means only the reported prefix was accepted. Code that requires the whole message must check the count and retry the unwritten suffix or report failure. Handling only the return from close leaves that earlier failure undetected. Writeback can batch multiple writes into larger requests to the device, which helps throughput but creates a period during which an acknowledged write may disappear after a crash.
A crash can also leave related changes at different stages. Imagine allocation metadata that says a block is free while a persisted inode already points to it. A subsequent allocation could assign that same block to a second file. Journaling and copy-on-write use ordered writes and a commit mechanism so recovery can find a consistent state. The exact promises for recently modified file data depend on the file system and its configuration. Crash consistency of the file system's own metadata and durability of an application's most recent update are distinct properties.
A program requiring durable data checks the result of synchronizing the file with fsync. For a newly created name it may also need to synchronize the containing directory, following the file system's guarantees. File data and the directory entry are separate persistent objects. Closing a descriptor releases a reference to an open file description, which is a lifetime operation. It does not substitute for checking the durability operations.
The performance question here resembles CPU scheduling. A device can often handle a batch more efficiently than many small operations sent independently. The kernel can choose when to start the batch, subject to the contract exposed to applications. The device driver supplies the mechanism to submit and complete requests. A batch that is too large can make a read wait behind unrelated writes, just as a long CPU slice can delay a newly ready process. Correct execution, responsiveness, and efficient resource use each need their own evidence.
Worked trace
Suppose save-note reads a number from an existing file, adds one, and rewrites the number. The file starts with 41. On a single core, trace two processes A and B. Assume each read or write succeeds and each writer writes a complete value. This isolates the logical race from partial writes and crash recovery.
- At time 0, the scheduler dispatches A. Its file read obtains
41, and A computes42in private memory. The kernel preempts it before the write. A still has the computed value when it next runs. - At time 5, B opens the same pathname independently. Its own descriptor and offset lead it to the same underlying file. It too reads
41, computes42, and writes42. The dirty data is visible through the file system's cache. - At time 10, A resumes and writes the value it calculated earlier. The file still contains
42after both processes complete. The CPU and memory virtualization behaved correctly. The two independent address spaces converged on shared file state. - If both synchronize their writes successfully,
42can become durable. That still loses one increment. Durability preserves the data that was actually written and cannot recover an update the application never computed.
Change one input
Let both invocations take the same exclusive application lock before reading and hold it until after writing. If A takes it first, predict the values B reads and writes. A writes 42 before releasing the lock. B then reads 42 and writes 43. Move the lock to surround only the write, and both reads can again see 41. The right critical section follows the lifetime of the assumption that the old value is current.
Continue to the process abstraction and its states.
Before you move on
Try it in your workspace
Trace what one program touches before it prints a line: CPU registers, virtual memory addresses, and disk persistence. Note which OS boundary separates policy from mechanism.
Keep a short note of what you tried, what passed, and what you still need to check.
0 of 3 checked.
Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.