While studying operating systems concepts, I saw the term trap instruction. "A TRAP instruction is performed to switch from user mode to kernel mode." I failed to understand what a trap instruction does.
-
1Have an explanation on [wikipedia](https://en.wikipedia.org/wiki/Trap_%28computing%29). – PJProudhon Mar 10 '18 at 08:59
3 Answers
There are two ways to enter kernel mode:
- Interrupt
- Exception
When either occurs, the processor dispatches to the appropriate handler in its interrupt dispatch table (or similar mechanism). This table is defined by the operating system.
A trap is an exception where the instruction cannot be restarted. In contrast, a fault is an exception where the instruction can be restarted.
Every processor I am aware of has some instruction that explicitly causes an exception in order to get into kernel mode. Such instructions are used to implement operating system services.

- 20,574
- 3
- 26
- 62
A trap is an exception in a user process. It's caused by division by zero or invalid memory access. It's also the usual way to invoke a kernel routine (a system call) because those run with a higher priority than user code. Handling is synchronous (so the user code is suspended and continues afterward). In a sense they are "active" - most of the time, the code expects the trap to happen and relies on this fact.
This answer from here might help.
I will give you an example to understand when to use fork
and what it does.
fork
duplicates almost all to the newly created child in this process. There is a duplication of trapframe
from parent to child. You may ask what the trapframe
is: It's a way to ensure that both the parent and the child complete running from the place you called fork
, so at the end both child and parent running this operation happen in kernel.
At the end, trap is to move to a permission place called kernel space. Every process has its own kernel space and in memory we have one kernel no duplication.

- 32,039
- 22
- 142
- 171

- 3,256
- 2
- 24
- 40
-
1Well, a little fixing of word order would not mind. It is a little hard to read. – Herdsman Jan 11 '20 at 20:23
There are 2 different meanings for "trap instructions":
- Interrupted instructions (for example, I/O interrupted instructions);
- Processor exception (for example, Data Abort (ARM), this exception occurs when a data transfer instruction attempts to load or store data at an illegal address.

- 103
- 2
- 6