Part 6 of 8 · 2 min read
Staying in control
Think of a school bell. Pupils do not choose when a lesson ends, and the bell hands control back to the teacher. A timer does that for the processor. The analogy stops in one place: a bell is heard by every pupil, and a timer interrupts one processor.
In plain words: The OS must be able to take the processor back. Before it starts a program it sets a timer, and when the timer fires an interrupt returns control to the kernel. A program that does something illegal causes a trap, and the kernel ends it or sends it a signal. So a program in user mode cannot hold the machine or damage the kernel.
A user program must not be able to keep the processor forever, or to harm the OS by a mistake. The hardware gives the OS two tools.
The timer. Before it hands the processor to a program, the OS sets a timer. When the timer counts down to zero, the hardware interrupts the processor, and control returns to the OS. A program stuck in an infinite loop therefore cannot freeze the machine. On Linux, the kernel setting HZ gives how many timer interrupts occur a second. With HZ = 250 there are 250 a second, one every 4 milliseconds (1,000 / 250). OSC adds a counter example: with a 10-bit counter driven by a clock that ticks every millisecond, the timer can be set anywhere from 1 up to 1,024 milliseconds.
The key lines.
Traps. If a program does something illegal, such as running a privileged instruction or touching memory that is not its own, the hardware traps to the OS. The OS then usually ends the program and may save a memory dump to a file for debugging. A tiny program shows this:
int main(void) {
int *p = 0;
*p = 42; /* address 0 is not mapped for this process */
return 0;
}
Running it in a shell:
Segmentation fault
exit=139
The exit code 139 is 128 plus 11, where 11 is the number of the signal for an invalid memory access. The OS, not the program, produced the message and the code. The machine itself stayed healthy.
So the OS cannot be harmed by a user program in user mode: the privileged instructions are blocked, memory outside the program's own is blocked, and the timer returns control. Those three together are the heart of protection.
Read it as
The kernel is not running while a user program runs. It gets control only through an event: a system call, a trap or an interrupt. Everything the OS does is a reaction to one of these three.
Check yourself: 1. What stops a user program from running forever? 2. How often is the timer interrupt with HZ = 100? 3. What produced the message "Segmentation fault"?