Skip to main content

System call; read() execution

Short answer

A system call is a user program's request to the kernel for privileged service, using a library procedure and a TRAP. For read(), parameters are pushed, the system-call number is placed in a register, TRAP switches to kernel; the dispatcher invokes the handler, which performs I/O and returns the byte count.

What is a system call? Illustrate the execution of the system call read() to read a file.

A system call is a request made by a user program to the operating system kernel to perform a privileged service. The call is made through a library procedure that executes a TRAP instruction to enter kernel mode.

Execution of count = read(fd, buffer, nbytes)

The call reads nbytes bytes from the file with descriptor fd into buffer and returns the number of bytes read (-1 on error). The steps (Tanenbaum) are:

  1. The program pushes the parameters (fd, buffer, nbytes) onto the stack (steps 1-3).
  2. The program calls the library procedure read (step 4).
  3. The library procedure puts the system-call number for read in a register (step 5).
  4. It executes a TRAP instruction, switching from user mode to kernel mode and jumping to a fixed address in the kernel (step 6).
  5. The kernel's dispatcher examines the system call number and uses it to index a table of pointers to the handlers (step 7).
  6. The read handler runs: it checks the parameters, finds the file, and starts the disk transfer, blocking the process if necessary (step 8).
  7. When the work is done, control returns to the library procedure after the TRAP instruction (step 9).
  8. The library procedure returns to the user program in the normal way, with the result as its return value (step 10).
  9. The user program cleans up the stack by incrementing the stack pointer (step 11) and continues.
 User space:  program --> read() library
                              | TRAP
 -----------------------------+------------
 Kernel space:  dispatcher -> table lookup
                              |
                         sys_read handler
                              |
                  disk driver / file system
                              |
                    return to library --> program

The user-mode to kernel-mode switch keeps the hardware protected, because user code cannot directly run privileged instructions.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Operating System chapter 1 questions →