The CPU normally executes a program one instruction after another.
However, some events require immediate attention. A network packet may arrive, a timer may expire, or the current instruction may attempt to access invalid memory.
When such an event occurs, the CPU temporarily stops its normal execution flow and transfers control to the operating system.
Interrupts, exceptions, and traps are different ways this transfer can happen.
They form the bridge between ordinary instruction execution and operating-system control.
During normal execution, the CPU uses the program counter to locate the next instruction, and if nothing unusual happens it simply keeps moving through the program.
But suppose a network device receives a packet while Instruction 2 is running. The operating system should process that event without waiting for the current application to finish.
The CPU needs a controlled way to pause the program, run operating-system code, and later resume the program.
A simplified flow looks like this:
Saving the execution state is what makes the detour invisible to the program. Instruction 3 runs exactly as it would have, with no knowledge that the kernel ran in between.
The nature of the event determines whether it is called an interrupt, exception, or trap.
An interrupt is an event that occurs independently of the instruction currently being executed.
It usually comes from hardware outside the CPU core.
Examples include a keyboard key being pressed, a network packet arriving, a storage device completing a read, or a timer expiring.
The application did not directly cause the interrupt. It may arrive between any two instructions.
For this reason, interrupts are described as asynchronous.
The packet arrives on its own schedule. The application did nothing to invite it, and the same interrupt could have landed between any other pair of instructions.
Without interrupts, the CPU would need to repeatedly ask every device whether something had happened.
Conceptually, it would keep asking whether the keyboard received input, whether the disk finished its operation, whether a packet arrived, and whether the timer expired.
This approach is called polling.
Polling can be useful in some situations, but continuously checking inactive devices wastes CPU time.
Interrupts allow a device to notify the processor only when attention is required.
The CPU can perform useful work while the device operates independently.
Timer interrupts are especially important to an operating system.
The operating system configures a hardware timer to generate an interrupt periodically. When the timer expires, control returns to the kernel.
This ensures that the operating system regains control even if the currently running program never voluntarily gives it up.
Timer interrupts make preemptive multitasking possible.
Program A does not choose between the two outcomes on the right, and it cannot refuse the interrupt. That is what separates preemptive multitasking from a system where a program keeps the CPU until it decides to give it up.
Scheduling will be covered separately. The important point here is that a timer interrupt gives the operating system an opportunity to make that decision.
An exception is generated because of the instruction currently being executed.
Unlike a hardware interrupt, an exception is synchronous. If the program runs again with the same state and reaches the same instruction, the same exception will usually occur again.
Common causes include attempting to divide by zero, executing an invalid instruction, accessing protected memory, or requesting a virtual-memory page that is not currently available.
The same hardware path leads to a recovered program or a terminated one, and the kernel handler decides which. The next two sections walk through one example of each.
Exceptions are not always errors.
Some are part of normal operating-system behavior.
A page fault, for example, can occur when a process accesses a valid virtual-memory page that has not yet been loaded into physical memory. The operating system can load the page and allow the instruction to run again.
Other exceptions represent invalid operations and usually cause the process to be terminated.
Consider:
The program attempts to read through a null pointer.
When the CPU executes the memory-access instruction, it detects that the process is not allowed to access that address.
The CPU raises an exception and transfers control to the kernel. The full sequence runs like this:
On Linux, the program commonly ends with a message such as:
The CPU detects the invalid access. The operating system decides what should happen to the process.
Now consider a process accessing a valid page that has not yet been loaded into physical memory.
The CPU cannot complete the instruction immediately, so it raises a page-fault exception.
The operating system checks the requested address. If the access is valid, it prepares the page, updates the memory mapping, and restarts the instruction.
The sequence starts the same way as the previous example but ends differently:
From the application’s perspective, nothing unusual may be visible.
This shows that an exception is not necessarily a program failure. It is a mechanism that allows the operating system to respond to conditions detected during instruction execution.
The word trap is used differently across processor architectures and operating-system textbooks.
In this course, we will use it to describe an intentional, synchronous transfer of control from a running program to a special handler.
A trap may be generated by an instruction specifically designed to enter the kernel or debugger.
Typical examples include system-call instructions and debugger breakpoints. The application intentionally executes a special instruction, the CPU transfers control to a predefined handler, the kernel or debugger performs an operation, and the application resumes.
Unlike a divide-by-zero exception, a trap is usually deliberate.
The application or debugging tool intentionally executes an instruction that requests special handling.
Applications run in user mode and cannot directly execute privileged operations.
When an application needs the operating system to open a file, create a process, or send network data, it uses a controlled entry mechanism.
On modern processors, this commonly involves a special system-call instruction.
The instruction causes a synchronous transition into kernel mode:
The program requests the transition, but it does not choose where execution lands. The kernel entry point is fixed in advance, which is what separates a system call from an arbitrary jump into privileged code.
Many operating-systems courses refer to this controlled transfer as a trap into the kernel.
The detailed system-call mechanism will be covered in a later chapter.
Debuggers also use traps.
When you set a breakpoint in GDB, the debugger can replace an instruction with a special breakpoint instruction.
When the CPU reaches that instruction, it generates a trap. Control is transferred to the debugger, which allows you to inspect registers, memory, variables, and the call stack.
The program is paused, not finished. It can later continue from the paused location.
The most useful distinction is based on where the event comes from and whether it is related to the current instruction.
| Event | Source | Timing | Example |
|---|---|---|---|
| Interrupt | External hardware | Asynchronous | Network packet arrives |
| Exception | Current instruction | Synchronous | Invalid memory access |
| Trap | Intentional instruction | Synchronous | System call or breakpoint |
An interrupt can occur regardless of what the current program is doing.
An exception occurs because of the instruction currently being executed.
A trap is commonly an intentional instruction used to request special handling.
The terminology is not completely universal. Some architectures use “exception” as a broad category that includes interrupts and traps. Some textbooks use “trap” for nearly every transfer into the kernel.
In interviews, it is useful to state the definition you are using before comparing them.
Loading simulation...
Although the details vary by architecture, the CPU generally performs a sequence like this:
Interrupts, exceptions, and traps differ only in what causes the first step. Everything after it is the same machinery. The saved state commonly includes the program counter and important processor registers.
Without saving this state, the CPU would not know where or how to resume the interrupted program.
The processor needs to know which code should handle each event.
The operating system configures a table containing handler locations.
Conceptually, it might look like this:
| Event | Handler |
| Timer interrupt | Timer handler |
| Keyboard interrupt | Keyboard handler |
| Page fault | Page-fault handler |
| Invalid instruction | Invalid-instruction handler |
| System-call entry | System-call handler |
When an event occurs, the processor identifies its event number and uses the table to find the correct handler.
The exact table and terminology depend on the CPU architecture.
On x86 systems, this mechanism is associated with the Interrupt Descriptor Table. Other architectures provide equivalent structures.
Loading simulation...
Hardware interrupts can arrive at inconvenient times.
The CPU may be executing application code or another operating-system operation when the event occurs.
Interrupt handlers are therefore designed to complete urgent work quickly.
A network interrupt handler, for example, may acknowledge the device and record that data is available. More expensive processing can be deferred until later.
Keeping handlers short reduces the time during which other important work may be delayed.
The operating system must also protect shared data that can be accessed by both ordinary kernel code and interrupt handlers.
These synchronization concerns will be covered later in the concurrency section.
Some events are more urgent than others.
Processors and interrupt controllers may support different interrupt priorities. A higher-priority event may be allowed to interrupt the handling of a lower-priority event.
The operating system can also temporarily prevent selected interrupts from being delivered. This is called interrupt masking or disabling interrupts.
Masking can protect very short critical operations inside the kernel, but it must be used carefully.
If interrupts remain disabled for too long, the system may delay timer events, network processing, and device completion notifications.
Some critical events cannot normally be masked. These are often called non-maskable interrupts and are reserved for severe hardware conditions.
Some processor documentation divides synchronous exceptions into three categories: faults, traps, and aborts.
A fault is detected before an instruction successfully completes. If the operating system fixes the problem, the instruction may be restarted. A page fault is the standard example.
A trap, in this narrower architectural meaning, is reported after the instruction completes. Breakpoint and debugging operations commonly behave this way.
An abort represents a severe condition for which reliable instruction restart may not be possible, such as certain hardware failures.
| Category | When it is reported | Recovery |
|---|---|---|
| Fault | Before the instruction completes | The instruction may be corrected and retried |
| Trap | After the instruction completes | The handler runs, then execution continues |
| Abort | Severe failure | Reliable restart may not be possible |
This narrower definition of trap is common in processor documentation, especially for x86.
In broader operating-system discussions, “trap” may instead mean any synchronous transfer into the kernel. Always use the surrounding context to determine which meaning is intended.
Linux exposes interrupt statistics through /proc/interrupts.
Run:
The output varies by machine, but it may contain rows for timers, storage devices, network devices, and other hardware.
A simplified example could resemble:
The columns show how many times each CPU core has handled a particular interrupt.
You can watch the values change:
While the command is running, move the mouse, type on the keyboard, or generate network traffic. On some physical Linux systems, relevant counters may increase.
Virtual machines, containers, and WSL may expose fewer hardware details or present interrupts differently.
Press Ctrl + C to stop watch.
Create a file named fault.c:
Compile it with debugging information:
Run it normally:
The program will likely terminate with a segmentation fault.
Now run it inside GDB:
At the GDB prompt, enter:
The debugger should stop at the instruction that attempted the invalid access.
Use:
to inspect the call stack, and:
to view the surrounding source code.
The complete flow is:
Interrupts allow the operating system to respond to hardware without constantly polling every device.
Exceptions allow the processor to report conditions caused by the current instruction, including both recoverable events and program errors.
Traps provide a controlled way for applications and debugging tools to request special handling.
Together, these mechanisms ensure that the operating system can regain control when hardware needs attention, when an instruction cannot continue normally, or when an application deliberately requests a protected service.
They also provide the foundation for several later topics:
| Mechanism | Topic it supports |
|---|---|
| Timer interrupts | CPU scheduling |
| Page faults | Virtual memory |
| System-call traps | Kernel services |
| Device interrupts | Input and output |
| Protection exceptions | Process isolation |
| Breakpoint traps | Debugging |
Think of the CPU as following a route through a program.
An interrupt is an external notification that temporarily pulls the CPU away from that route.
An exception is a condition discovered while following the route.
A trap is commonly an intentional checkpoint placed in the route to transfer control to the kernel or debugger.
In each case, the CPU pauses normal execution, saves enough state to understand where it was, and runs a predefined handler.
Interrupts, exceptions, and traps allow the CPU to stop its normal instruction sequence and transfer control to special operating-system code.
Interrupts are asynchronous events that usually originate from hardware. Exceptions are synchronous conditions caused by the instruction currently executing. Traps are commonly intentional synchronous events used for operations such as system calls and debugger breakpoints.
The CPU preserves execution state, identifies the event, and runs an appropriate handler. After the event is handled, the interrupted program may continue, retry an instruction, or be terminated.
The most important distinction is:
Interrupts come from outside the current instruction, while exceptions and traps are caused by the current instruction flow.
5 quizzes