Definition
Trap
A trap (or synchronous interrupt) is an exception generated by the CPU itself as a direct result of the current instruction being executed. Traps are synchronous events, meaning they occur at a deterministic point in the code execution.
Causes
Traps generally fall into two categories:
- Error Traps: Triggered by illegal operations, such as:
- Division by zero.
- Invalid machine code (illegal opcode).
- Memory access violations (e.g., segmentation faults).
- Service Traps: Intentional triggers used to request services from the OS, such as:
- Supervisor Calls (System Calls) for I/O operations.
- Breakpoints used during debugging.
Role in Mode Switching
When a trap occurs, the hardware automatically performs a mode switch to Kernel Mode, allowing the OS to gain control and handle the error or fulfil the service request.