13

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.

Borhan Rabbani
  • 131
  • 1
  • 1
  • 5

3 Answers3

9

There are two ways to enter kernel mode:

  1. Interrupt
  2. 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.

user3344003
  • 20,574
  • 3
  • 26
  • 62
2

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
zerocool
  • 3,256
  • 2
  • 24
  • 40
1

There are 2 different meanings for "trap instructions":

  1. Interrupted instructions (for example, I/O interrupted instructions);
  2. 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.
Roman Voyt
  • 103
  • 2
  • 6