System Calls
- An API to the OS
- A way to call facilities/services in the kernel
- Similar to a normal function call, but not the same: needs to change from user to kernel mode
Unix syscalls
- In c/c++, syscalls can be invoked almost directly
- There is a library version of all syscalls (with the same name & parameters), acting as a function wrapper
- There are also simplified, user friendly library versions, with less parameters?
- e.g.
printf() calls the write() syscall
strace <program> runs the program, and displays all syscalls made
Syscall Mechanism
- User program invokes the library fn (using normal function call mechanism)
- Library fn (usually in assembly) places syscall number in designated location e.g. a register
- Syscall number: number that identifies syscall, depends on system e.g. 39→
getpid
- Library fn executes a special instruction to switch frm user mode to kernel mode, commonly
TRAP. This saves the current context (cpu state)
- Now in kernel mode, the syscall handler is determined by a dispatcher (switch statement based on syscall number)
- Syscall handler is executed
- Restore context (CPU state), return to library fn, switch frm kernel to user mode
- Library fn returns to user program (using normal function mechanism)
Non-intentional Interaction
Exception
- Executing a machine level instruction can cause exception, e.g. arithmetic error: divide by zero, memory error: illegal memory address
- Synchronous: Occurs due to program execution
- Exception handler: Executed automatically in the kernel when exception happens. (
TRAP into kernel, run exception handler)
Interrupt
- External events can cause interrupts, usually hardware related e.g. timer, mouse movement, keyboard press
- Asynchronous: Not due to program execution
- Interrupt handler: Execution is suspended, and an interrupt handler is automatically executed
Mechanism
- Exception/interrupt occurs
- CPU transitions to kernel mode, transfers control to a handler automatically
- Save context
- Perform handler routine (may impact the program e.g.
ctrl + c keyboard interrup)
- Restore context, return from interrupt