In OS Structure & Kernel we saw that user programs run in user mode and cannot touch hardware or other programs' memory. But real programs constantly need to do things that only the kernel can do: read a file, print to the screen, send data over the network, create a new process.
So how does a program in user mode get these things done? It politely asks the kernel. That request is called a system call.
In this chapter we will learn what a system call is, what exactly happens inside the CPU and the kernel during one, the main types of system calls, and we will watch real system calls being made by a C program on Linux.
What Is a System Call?
A system call is the programmatic way in which a program requests a service from the operating system kernel. It is the only controlled entry point through which a user-mode program can make the kernel do privileged work on its behalf.
A simple analogy is a bank. You (the user program) are not allowed to walk into the vault (hardware, kernel memory). Instead you fill a form and hand it over at the counter (the system call). The bank staff (the kernel) checks the form, checks that you are allowed to do this, does the work inside the vault, and hands you the result.
Some everyday actions and the Linux system calls behind them:
What your program does | System call(s) used |
|---|---|
Open a file |
|
Read from a file or the keyboard |
|
Print to the screen or write to a file |
|
Ask for more memory |
|
Create a new process |
|
Run another program |
|
Finish the program |
|
Why Not Just Call a Kernel Function Directly?
Because then the program would be running kernel code with user-mode privileges (which would fail), or it would need kernel privileges (which would destroy protection). A system call solves this neatly:
The CPU switches to kernel mode only by jumping to a fixed entry point that the kernel set up during boot. The program cannot choose an arbitrary kernel address.
The kernel validates every argument (is this file descriptor yours? does this buffer address belong to you?) before doing anything.
When done, the CPU switches back to user mode before the program continues.
So protection is kept, and the program still gets the service it needs.
How a System Call Works, Step by Step
Let us follow a single call: a C program calls write(1, "Hi\n", 3) to print to the screen. We will use Linux on an x86-64 CPU as the concrete example.
USER MODE
+----------------------------------------------------------+
| 1. Program calls the C library function write(1, buf, 3) |
| 2. The library wrapper puts: |
| rax = 1 (system call number for write) |
| rdi = 1, rsi = buf, rdx = 3 (the arguments) |
| 3. Executes the special 'syscall' instruction |
+----------------------------------------------------------+
| CPU switches to kernel mode and jumps
v to the kernel's system call entry point
KERNEL MODE
+----------------------------------------------------------+
| 4. Kernel saves the user program's registers |
| 5. Looks up entry 1 in the system call table -> write |
| 6. Runs the kernel's write code: checks fd 1 is valid, |
| checks buf is readable user memory, sends the bytes |
| to the terminal driver |
| 7. Puts the return value in rax (3 = bytes written, |
| or a negative error code) |
| 8. Restores registers, returns with 'sysret' |
+----------------------------------------------------------+
| CPU switches back to user mode
v
USER MODE
+----------------------------------------------------------+
| 9. Library wrapper checks rax. If it is an error, it |
| stores the error number in errno and returns -1. |
| Otherwise it returns the value (3). |
+----------------------------------------------------------+
A few important details from this picture:
System Call Number
Each system call has a number. The kernel keeps a system call table: an array where index n holds the address of the kernel function for system call n. The program passes only the number, never a kernel address. That is part of what makes it safe.
The numbers depend on the OS and the CPU architecture. On x86-64 Linux, write is 1 and getpid is 39 (you will see this printed by a real program below). On 32-bit x86 Linux, the numbers are different.
The Trap Instruction
The instruction that crosses into the kernel is often called a trap or software interrupt. Different CPUs have different ones:
Architecture | Instruction |
|---|---|
x86-64 |
|
32-bit x86 (older Linux) |
|
ARM64 |
|
RISC-V |
|
Passing Parameters to the Kernel
There are three general methods, and exam questions love this:
In registers – fastest. Linux x86-64 passes up to six arguments in registers
rdi, rsi, rdx, r10, r8, r9, with the call number inrax.In a block (table) in memory – the parameters are stored in memory and only the address of the block is passed in a register. Useful when there are many parameters or large structures.
On the stack – the program pushes parameters onto the stack and the kernel pops them.
Methods 2 and 3 have no limit on the number or length of parameters. Real systems often combine them; for example, the registers hold small values plus pointers to bigger structures in memory.
Return Values and errno
The kernel returns a result in a register. On Linux, a value from -4095 to -1 means an error (for example, -2 means "no such file"). The C library wrapper converts this into the usual convention: it returns -1 and sets the global variable errno to the positive error code. That is why C code always checks for -1 and then looks at errno.
System Call vs Library Function (API)
Most programmers almost never execute the syscall instruction themselves. Instead they use an API (Application Programming Interface) provided by a library:
On Linux/UNIX: the C library (
glibc,musl) and the POSIX API.On Windows: the Windows API (Win32), in libraries such as
kernel32.dll. These call lower-level native system calls inntdll.dll.
Your code: printf("Hi\n");
|
v
C library: printf() formats the text, stores it in a buffer,
and later calls the write() wrapper
|
v
write() wrapper: sets up registers, executes 'syscall'
|
------------------|---------------- user/kernel boundary ----
v
Kernel: sys_write() does the real work
Why use an API instead of raw system calls?
Portability: a program using POSIX
write()compiles on Linux, macOS and BSD even though their system call numbers differ.Simplicity: the API hides register details and error conventions.
Efficiency: library functions like
printfandfreadbuffer data, so many small prints become a singlewritesystem call.
Important: not every library function is a system call.
strlen(),sqrt()andqsort()never enter the kernel.printf()is a library function that may eventually call thewritesystem call.write()itself is a thin wrapper around thewritesystem call.
Three Ways to Print, Side by Side
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
int main(void) {
/* 1. C library function (buffered, may call write() later) */
printf("1. printf\n");
fflush(stdout);
/* 2. POSIX wrapper function for the write system call */
write(STDOUT_FILENO, "2. write\n", 9);
/* 3. Generic syscall() wrapper with the system call number */
syscall(SYS_write, STDOUT_FILENO, "3. syscall(SYS_write)\n", 22);
printf("SYS_write number on this machine = %d\n", SYS_write);
printf("SYS_getpid number on this machine = %d\n", SYS_getpid);
return 0;
}Output on x86-64 Linux (compiled with gcc -std=c17 -Wall -Wextra):
1. printf
2. write
3. syscall(SYS_write)
SYS_write number on this machine = 1
SYS_getpid number on this machine = 39All three lines reach the screen through the same write system call; they just enter it from different levels. The fflush(stdout) after the first printf forces the library to empty its buffer immediately, otherwise the order of lines could change when output is redirected to a file.
Watching Real System Calls with strace
On Linux, the strace tool shows every system call a program makes. Consider this tiny program:
#include <unistd.h>
int main(void) {
const char msg[] = "Hello from write()\n";
write(1, msg, sizeof msg - 1); /* 1 = standard output */
return 0;
}Running strace ./hello_write prints a surprisingly long list. Here are the first and last few lines from a real run (strace prints to standard error; the program's own "Hello from write()" output, which gets mixed into the terminal, has been removed for clarity):
execve("./hello_write", ["./hello_write"], 0x7fffa2f5e7e0 /* 21 vars */) = 0
brk(NULL) = 0x58447b4cd000
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x702a5799a000
...
openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0 \250\2\0\0\0\0\0"..., 832) = 832
...
write(1, "Hello from write()\n", 19) = 19
exit_group(0) = ?
+++ exited with 0 +++What does this tell us?
execveloads the program. Even starting a program is a system call.Before
main()runs, the dynamic loader usesopenat,readandmmapto load the C library (libc.so.6) into memory. Your one-line program depends on many system calls you never wrote.Our
writeappears aswrite(1, "Hello from write()\n", 19) = 19: file descriptor 1, the bytes, the length, and the return value 19 (bytes written).Returning from
mainleads toexit_group(0), which ends the process.
A Practical Example: Copying a File
Copying a file is a classic textbook example because it uses several kinds of system calls in sequence: open the input, create the output, read and write in a loop, then close both.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "usage: %s <source> <dest>\n", argv[0]);
return 1;
}
int in = open(argv[1], O_RDONLY); /* system call */
if (in == -1) { perror("open source"); return 1; }
int out = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644); /* system call */
if (out == -1) { perror("open dest"); close(in); return 1; }
char buf[4096];
ssize_t n;
while ((n = read(in, buf, sizeof buf)) > 0) { /* system call */
if (write(out, buf, n) != n) { /* system call */
perror("write");
return 1;
}
}
if (n == -1) perror("read");
close(in); /* system call */
close(out); /* system call */
printf("copied %s -> %s\n", argv[1], argv[2]);
return 0;
}With a small file notes.txt containing two lines, we trace only the file-related calls (-e trace=openat,read,write,close). The lines before ours (loading libc) are omitted:
openat(AT_FDCWD, "notes.txt", O_RDONLY) = 3
openat(AT_FDCWD, "copy.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644) = 4
read(3, "line one\nline two\n", 4096) = 18
write(4, "line one\nline two\n", 18) = 18
read(3, "", 4096) = 0
close(3) = 0
close(4) = 0
write(1, "copied notes.txt -> copy.txt\n", 29) = 29
+++ exited with 0 +++Notice:
The C function
open()actually used theopenatsystem call. Library names and kernel names do not always match.The kernel handed out file descriptors 3 and 4, because 0, 1 and 2 are already used by standard input, output and error.
The second
readreturned 0, which means end of file, so the loop stopped.The
printfat the end became a singlewrite(1, ...)call.
When a System Call Fails
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
int fd = open("does_not_exist.txt", O_RDONLY);
if (fd == -1) {
printf("open() returned -1, errno = %d (%s)\n", errno, strerror(errno));
perror("open");
return 1;
}
close(fd);
return 0;
}Output in a terminal:
open() returned -1, errno = 2 (No such file or directory)
open: No such file or directoryAnd strace shows what the kernel really returned:
openat(AT_FDCWD, "does_not_exist.txt", O_RDONLY) = -1 ENOENT (No such file or directory)The kernel reported the error ENOENT (value 2); the library wrapper turned it into a return value of -1 and set errno = 2. Always check the return value of system calls; ignoring errors is one of the most common bugs in systems code.
Types of System Calls
System calls are usually grouped into six categories. The table gives typical UNIX/Linux and Windows API examples.
Category | What it covers | UNIX / Linux | Windows API |
|---|---|---|---|
Process control | Create, run, wait for, terminate processes |
|
|
File management | Create, open, read, write, close, delete files |
|
|
Device management | Request and release devices, read/write, control them |
|
|
Information maintenance | Get/set time, process IDs, system data |
|
|
Communication | Send/receive messages, shared memory between processes |
|
|
Protection | Get/set permissions on resources |
|
|
On UNIX, devices are treated as special files (like /dev/sda or /dev/tty), so the same read and write calls work for both files and devices. That is a big design simplification.
Many of these system calls get their own chapters later: fork/exec/wait in Process Creation (fork & exec), and pipe/shared memory in Inter-Process Communication.
How Expensive Is a System Call?
A system call is much more expensive than a normal function call because the CPU must switch modes, the kernel must save and restore registers, validate arguments, and on modern CPUs apply security mitigations at the boundary. That is a few hundred nanoseconds or more, compared to a few nanoseconds for a plain function call (exact numbers vary greatly by CPU and kernel).
This is why:
Libraries buffer I/O:
printfcollects text and makes onewriteinstead of many.Reading a file 4 KB at a time is far faster than reading it 1 byte at a time, even though both read the same data.
Linux provides the vDSO (virtual dynamic shared object): a few very frequent read-only calls such as
clock_gettime()andgettimeofday()are answered by code mapped into the process, usually without entering the kernel at all.
Mode switch vs context switch: a system call is a mode switch (user mode to kernel mode and back, in the same process). It does not necessarily cause a context switch (switching the CPU to a different process). A context switch happens only if the kernel decides to run another process, for example because the call has to wait for the disk. Context switching is explained in Process Control Block & Context Switching.
System Calls, Interrupts and Exceptions
All three transfer control to the kernel, but for different reasons:
Event | Caused by | Synchronous? | Example |
|---|---|---|---|
System call (trap) | The program, on purpose | Yes – happens at a specific instruction |
|
Exception (fault) | The program, by accident or for a special case | Yes | Divide by zero, invalid memory access, page fault |
Hardware interrupt | A device, independent of the running program | No – can arrive at any time | Key press, disk done, timer tick, network packet |
Common Mistakes
"printf is a system call." No. It is a library function that formats text and, when its buffer is flushed, calls the
writesystem call.Not checking return values.
open,readandwritecan fail or do partial work.writemay write fewer bytes than asked;readreturns 0 at end of file.Thinking every system call causes a context switch. Many (like
getpid) return immediately to the same process; only blocking calls lead to switching processes.Assuming system call numbers are universal. They differ between operating systems and even between CPU architectures of the same OS. That is why programs use library APIs.
Mixing
printfandwritewithout flushing.printfoutput sits in a user-space buffer;writegoes straight to the kernel. Output may appear out of order unless youfflush.
Interview Questions
What is a system call?
A controlled request from a user program to the kernel for a privileged service such as file I/O, process creation or memory allocation. It switches the CPU from user mode to kernel mode through a trap instruction and back afterwards.
What happens when a system call is made?
The library wrapper places the system call number and arguments in registers and executes a trap instruction (syscall on x86-64). The CPU switches to kernel mode and jumps to the kernel entry point, which saves registers, looks up the handler in the system call table, validates arguments, does the work, puts the result in a register, and returns to user mode. The wrapper converts errors into -1 and errno.
What are the ways to pass parameters to a system call?
In registers; in a block/table in memory whose address is passed in a register; or on the stack.
Difference between a system call and an API?
An API (like POSIX or the Windows API) is a set of library functions that programmers call. Some API functions are thin wrappers around system calls, some use several system calls, and some (like strlen) use none. APIs give portability and convenience.
Name the types of system calls with examples.
Process control (fork, exit, wait), file management (open, read, close), device management (ioctl), information maintenance (getpid, time), communication (pipe, socket, shmget), protection (chmod, chown).
Is a system call the same as a context switch?
No. A system call is a mode switch within the same process. A context switch (changing which process runs) happens only if the kernel decides to schedule another process, for example when the call blocks.
How can you see which system calls a program makes on Linux?
Use strace (for example strace ./program, or strace -c for a summary count).
Summary
A system call is the only controlled way for a user-mode program to request kernel services.
It works through a trap instruction (
syscall,svc,ecall) that switches to kernel mode and jumps to a fixed entry point. The kernel uses the system call number to find the handler in the system call table.Parameters are passed in registers, a memory block, or on the stack. Errors come back as -1 with
errnoset.Programs usually use an API (C library / POSIX, Windows API) instead of raw system calls, for portability, simplicity and buffering.
Six types: process control, file management, device management, information maintenance, communication, protection.
System calls are relatively expensive mode switches, which is why libraries buffer I/O. They are not the same as context switches.
stracelets you watch real system calls on Linux.
Next, in Processes & Process States, we look at the thing that makes all these system calls: the process.