Sub topic 2
System Calls: How a Program Asks the Kernel for Help
Prerequisites
Assume you know basic C syntax, pointers, CPU registers, memory, and interrupts. You should also know that the operating system (OS) controls hardware and provides services to programs.
The User–Kernel Boundary
A normal program runs in user mode, a restricted CPU mode. It cannot directly access device registers, change page tables, or perform privileged instructions. This restriction prevents one program from damaging the OS or another program.
The OS runs in kernel mode, which has the privileges needed to manage the CPU, memory, files, devices, and processes. A program crosses this boundary through a system call. A system call is a controlled request for a service provided by the kernel.
Common system calls include:
readandwritefor file or device input and outputopenandclosefor filesforkfor process creationwaitfor collecting a terminated child processexecfor replacing a process's program
A C library often provides a wrapper function around the system call. The wrapper places the call number and arguments in agreed locations, such as registers, and executes a special trap instruction.
The trap is a synchronous transfer caused by the running program. The CPU saves enough information to resume the program, changes to kernel mode, and jumps to a predefined kernel entry point. The kernel examines the system-call number, validates the arguments, performs the operation, and places a result in a register. It then executes a return-from-trap operation, restoring user mode.
System Calls and Interrupts
A hardware interrupt usually comes from outside the current instruction stream, such as a timer or network device. A system call is requested deliberately by the program. Both mechanisms transfer control to the kernel, but they have different causes.
A timer interrupt lets the scheduler regain control and preempt a running process. A system call normally blocks only when its requested operation cannot finish immediately, such as reading from an empty pipe.
Checking Results
System calls report success or failure. For example, write returns the number of bytes written, or -1 on failure. In that case, the C library sets errno, which describes the error.
#include <stdio.h>
#include <unistd.h>
int main(void) {
const char message[] = "hello\n";
ssize_t written = write(STDOUT_FILENO, message, sizeof(message) - 1);
if (written == -1) {
perror("write");
return 1;
}
return 0;
}Exercise
Why does a user program need a system call to write to a terminal instead of accessing the terminal hardware directly?
Show answer
Direct hardware access requires kernel privileges. The system call lets the kernel validate the request and perform the operation safely.