Sub topic 2
System Calls: How a Program Asks the Kernel for Help
This chapter assumes you know basic C and how a CPU handles interrupts. You should also know the previous chapter's idea that the CPU runs in user mode or kernel mode, selected by a mode bit. Here you will follow one request from a user program into the kernel and back.
Why system calls exist
A user program cannot touch the disk, the network card or another process's memory. Privileged instructions fail in user mode. The hardware raises an exception, and the kernel usually terminates the program.
A program still needs these services, so the kernel offers a fixed set of entry points called system calls. A system call is a controlled request from user code to the kernel. The program cannot jump to arbitrary kernel code. It can only ask for one of the listed services by number.
The trap mechanism
A system call is made with a special instruction that raises a trap. A trap is a synchronous, software-generated interrupt. The instruction is syscall on x86-64, svc on ARM, and int 0x80 on older 32-bit x86. In GATE questions the same idea is called a software interrupt.
The steps are:
- The program places the system call number and its arguments in agreed locations.
- It executes the trap instruction.
- The hardware switches the mode bit to kernel mode and saves the user program counter and flags. It then jumps to a fixed kernel entry address.
- The kernel looks up the call number in the system call table, an array of function pointers, and runs the matching handler.
- The kernel stores the result in a return register and executes a return-from-trap instruction. This restores user mode and the saved program counter.
The trap is the only way into the kernel for this purpose. The hardware chooses the entry address, not the program. That keeps the kernel safe from callers that would otherwise run code at a place of their choosing.
Wrappers, numbers, and the API
Most programmers never write the trap instruction. They call a function such as write from the C library. That function is a wrapper. It loads the call number and arguments into registers, executes the trap, and converts the kernel's answer into a normal C return value.
Programs see an API (application programming interface), such as POSIX. The API function and the system call underneath are different things. Some API functions make no system call. Others make several.
| Call | Layer | What it does |
|---|---|---|
| `write(fd, buf, n)` | System call wrapper | Always traps into the kernel |
| `printf("hi\n")` | Library function | Formats text, buffers it, and calls `write` later |
| `strlen(s)` | Library function | Runs entirely in user mode, with no trap |
| `fork()` | System call wrapper | Creates a new process |
The wrapper hides the call number. Each call has a number, and the table maps it to a handler. On x86-64 Linux, write is number 1.
You can bypass the wrapper with the generic syscall function:
#define _GNU_SOURCE
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(void) {
const char *msg = "hello via raw syscall\n";
long n = syscall(SYS_write, 1, msg, strlen(msg));
return n < 0 ? 1 : 0;
}The program writes to file descriptor 1, which is standard output. The kernel sees exactly the same request that write or printf would eventually produce.
Passing parameters
A system call may need more data than fits in a few registers. There are three common methods:
- Registers. The simplest and fastest method. It is limited by the number of registers.
- A block in memory. The arguments sit in a table, and one register holds the table's address. Linux uses this for calls with many arguments.
- The stack. The program pushes the arguments, and the kernel pops them.
Block and stack passing do not limit the number or length of arguments. Whatever the method, the kernel must validate every pointer it receives. A user program could pass an address inside kernel memory or an unmapped address. The kernel checks that the address belongs to the caller before it reads or writes there.
Families of system calls
The usual textbook grouping is the one GATE uses:
- Process control:
fork,exec,exit,wait - File management:
open,read,write,close - Device management:
ioctl,read,writeon device files - Information maintenance:
getpid,time - Communication:
pipe,shmget,socket
Errors and return values
Most POSIX system calls return -1 on failure. They put a reason code in the global variable errno. Check the return value first. errno is only meaningful after a call has failed.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void) {
int fd = open("/no/such/file", O_RDONLY);
if (fd == -1) {
printf("open failed: errno=%d (%s)\n", errno, strerror(errno));
return 1;
}
close(fd);
return 0;
}This prints errno=2 (No such file or directory). A successful open returns a small non-negative integer, the file descriptor.
Cost and the link to context switching
A system call is cheaper than a process context switch but dearer than a normal function call. It needs a mode change, a saved and restored user state, and argument checks. It does not switch to a different process, so it does not change the memory map. A blocking call such as read on an empty pipe can lead to a context switch. The kernel puts the caller in the waiting state and schedules another process.
This explains why printf buffers. Calling write once per character would pay the trap cost for each character. The library collects text in a buffer and makes one write call for the whole block.
Common mistakes
Other frequent errors:
- Assuming a trap and a hardware interrupt are the same. A trap is caused by the running instruction and happens at a predictable point. A hardware interrupt comes from a device at an arbitrary time.
- Forgetting that the mode bit is set back to user mode on return. The kernel never leaves a program running in kernel mode by accident.
- Reading
errnoafter a successful call. Its value may be left over from an earlier failure.
Exercise
A C program calls printf three times, each printing one line, and the output goes to a terminal. Name the instruction type that moves the CPU from user mode to kernel mode when a line is finally written, and say which mode runs the handler.
Show answer
The program executes a trap instruction (such as syscall). This is a software interrupt. The wrapper for write issues it, and the handler runs in kernel mode. The mode bit returns to user mode when the return-from-trap instruction executes.
Exercise
Which of these never needs a mode change: getpid(), strlen(s), open(path, flags), fork()? Explain why the other three do.
Show answer
strlen(s) never needs it. It only reads user memory and runs in user mode. getpid, open and fork read or change kernel data (process table, file table), so each needs a trap into the kernel.
Exercise
A system call needs eight arguments, but the machine has only five argument registers. Give one method that solves this and say what the kernel must check.
Show answer
Store the arguments in a block in memory and pass the block's address in a register (or push them on the stack). The kernel must validate the block's address and every pointer inside it, so a user program cannot make the kernel touch memory the program does not own.