Foundations: What an Operating System Is

a trap (software interrupt)

A trap is the mechanism that actually carries control from a user program into the kernel — the act of crossing through the teller window. If a system call is the request, the trap is the controlled jump that delivers it. The word captures the idea well: the program is deliberately caught and lifted out of its normal flow, set down safely inside the OS, and later returned. Because it is triggered on purpose by a software instruction, it is also called a software interrupt.

Here is the sequence. The program executes a special trap instruction (different chips name it differently, but its job is the same). The hardware does several things at once: it switches the mode bit to kernel, saves enough of the program's state (such as where it was) so it can be resumed, and jumps to a fixed kernel entry point recorded in a table the kernel set up at boot. The kernel then handles the cause — for a system call it dispatches to the right service; it uses the very same trap machinery for synchronous errors too, such as dividing by zero, dereferencing a bad address, or a page fault. When done, the kernel executes a return-from-trap instruction that restores the saved state and flips the mode bit back to user, and the program continues as if it had made an ordinary call.

Traps are worth distinguishing from ordinary (hardware) interrupts. A trap is synchronous — it is caused by the currently running instruction (a deliberate syscall or an error in that instruction) and happens at a predictable point. A hardware interrupt is asynchronous — it is caused by an outside device (a key pressed, a packet arriving) and can strike between any two instructions. Both use the same basic plumbing to switch into the kernel, which is why the umbrella term is sometimes just interrupt; the key difference is whether the cause was inside the running program (trap) or outside it (interrupt).

Two ways into the kernel, both via the trap machinery: you call write() — a deliberate trap that enters the kernel to do the I/O; or your code accidentally divides by zero — the CPU traps on that very instruction, and the kernel decides what to do (usually killing the program with an error).

The same controlled jump handles both intended syscalls and unintended errors.

Trap is synchronous (caused by the running instruction); a hardware interrupt is asynchronous (caused by an external device). They share the entry machinery, but mixing up the two causes is a common beginner error.

Also called
software interrupttrapsynchronous interrupt軟體中斷陷阱