Skip to content
systemcoding.dev
Kernels

The Complete Guide to Linux System Calls

A working guide to Linux system calls: invocation, error returns, the main families with code, tracing with strace, seccomp filtering and portability.

28 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and FreeBSD logos.

Everything a Linux program does that touches the outside world goes through system calls. Reading a file, starting a process, allocating a page, accepting a connection, reading the clock: each is a request to the kernel through a narrow, well-defined interface, and the whole interface is a few hundred numbered entry points. Knowing how that interface works makes you better at debugging, at performance work, at security and at reading other people's code. This guide takes the subject from the instruction that crosses the boundary to the practical habits that keep programs correct. Examples use C on x86-64 with Linux 6.12 and glibc 2.40, and the register details are given for ARM64 and RISC-V where they differ. Every code listing is written to be complete and is followed by the output it produces.

What a system call is for

A modern CPU runs programs at two or more privilege levels. The kernel runs at the most privileged level and can touch hardware, page tables and other processes' memory. Ordinary programs run at the least privileged level, where those operations fault. A program that wants anything only the kernel can provide must ask, and the system call is the mechanism: a controlled transfer of execution into the kernel at an entry point the kernel chose, with arguments in registers, returning with a result.

The interface solves three problems at once. It protects the system, because the kernel validates every request and a program cannot reach beyond what it was granted. It abstracts hardware, because write works the same on a disk, a terminal and a pipe. And it multiplexes resources, because the kernel decides which of a hundred processes gets the disk next. Nothing in a program's own code can do those things, which is why even a program that does nothing must make at least one call, exit_group, to end.

A useful mental model is a counter at a bank. You fill in a form (the registers), hand it across, and wait. The teller checks your identity and the form, does the work behind the glass, and hands back a receipt (the return value). You never walk into the vault. The rest of this guide fills in each part of that picture.

How a call crosses the boundary

On x86-64 the instruction is syscall. Before executing it, the program places the call number in rax and up to six arguments in rdi, rsi, rdx, r10, r8 and r9, in that order. The instruction saves the next instruction's address in rcx and the flags in r11, switches to the kernel privilege level and jumps to the address the kernel stored in the LSTAR register at boot. The kernel's entry code saves the user registers into a structure called pt_regs, switches to a kernel stack, looks the number up in a table and calls the matching function. When that function returns, the result is written into rax, the registers are restored and a return instruction (sysretq) goes back to user mode. The kernel's own names for these pieces are entry_SYSCALL_64 in arch/x86/entry/entry_64.S and do_syscall_64 in arch/x86/entry/common.c.

Other architectures follow the same shape with different details:

x86-64ARM64RISC-V 64
Trap instructionsyscallsvc #0ecall
Numberraxx8a7
Argumentsrdi rsi rdx r10 r8 r9x0 to x5a0 to a5
Resultraxx0a0

The numbers differ too. write is 1 on x86-64 and 64 on ARM64 and RISC-V, and exit_group is 231 on x86-64 and 94 on the others. The syscall(2) manual page is the reference for the conventions, and the kernel's syscall_64.tbl and the generic asm-generic/unistd.h hold the numbers. You rarely need them, because the C library hides them, but they matter when you read a trace, write a filter or work in assembly.

Three ways to make a call

There are three levels at which a program can invoke the kernel, and knowing which one you are using explains much of the behavior you will see.

The library wrapper is the normal route. You call write() and glibc's wrapper arranges the registers, executes the instruction and converts the result into the errno convention. The wrapper may add behavior: cancellation points for threads, restarting logic, and sometimes a different underlying call, so open() is implemented with openat and fork() with clone.

**The generic syscall() function** takes the number as its first argument and passes the rest through. It is the way to call something the library does not wrap yet:

getpid_raw.cc
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>

int main(void)
{
	long a = syscall(SYS_getpid);
	long b = getpid();

	printf("syscall(SYS_getpid)=%s getpid()\n", a == b ? "same as" : "different from");
	return 0;
}
Text
syscall(SYS_getpid)=same as getpid()

Inline assembly issues the instruction yourself, with no library at all. This is how a language runtime without libc, or a tiny freestanding program, works. The constraint letters bind each variable to a register: a is rax, D is rdi, S is rsi, d is rdx. The clobbers rcx and r11 are required because the instruction overwrites them:

raw.cc
static long raw_write(int fd, const void *buf, unsigned long len)
{
	long ret;

	__asm__ volatile ("syscall"
			  : "=a"(ret)
			  : "a"(1L), "D"((long)fd), "S"(buf), "d"(len)
			  : "rcx", "r11", "memory");
	return ret;
}

Use the wrapper unless you have a reason not to. The reasons are real but few: a call that is too new for your library, a runtime that avoids libc, or a deliberate test of the kernel boundary.

The result and the error convention

The kernel returns one value. A non-negative number is success. A value from -4095 to -1 is an error, the negation of an error code such as ENOENT (2) or EBADF (9). The reserved range exists so that large legitimate results, such as addresses returned by mmap, never collide with errors. The C library checks for that range after every call: if it matches, it stores the positive code in the thread-local errno and returns -1; otherwise it returns the value unchanged.

Two habits prevent most error-handling bugs. First, check every call whose failure you can handle, and decide deliberately about the ones you cannot. Second, read errno immediately after the failing call, or save it, because any later library call may overwrite it. The text comes from strerror(errno), and perror("label") prints it to standard error.

Some calls break the "-1 and errno" pattern, and the manual page for each says so. The POSIX thread functions return the error number directly. mmap returns MAP_FAILED, which is (void *)-1. getpriority can legitimately return -1, so you clear errno first and test it after. Read the RETURN VALUE section of a manual page the first time you use a call. A dedicated post in this cluster follows the error path from kernel to errno in detail.

Reading section 2 of the manual

The reference for every call is section 2 of the manual, man 2 open. The page has a fixed layout and each part tells you something you will need:

  • SYNOPSIS names the header files to include and the exact prototype. Feature-test macros such as _GNU_SOURCE appear here.

  • DESCRIPTION gives the semantics, flag by flag.

  • RETURN VALUE states how failure is signalled.

  • ERRORS lists every error code the call can return and the condition for each. This list is the contract you handle in code.

  • VERSIONS and STANDARDS state when the call appeared in Linux and which standard defines it.

  • NOTES gives differences between the C library wrapper and the raw kernel call, which matter when you use syscall().

The Linux man-pages project documents the kernel interface, and the pages are the primary reference alongside the kernel source. When a page says the call "was added in Linux 5.9", that is your version floor.

File I/O: open, read, write, close

The first family to master is file I/O, because in Unix almost everything is a file descriptor. open and openat turn a path into a small integer, read and write move bytes, lseek moves the position, and close releases the descriptor. The key facts are about what these calls do not promise. A read may return fewer bytes than requested, a write may write fewer than asked, and either may fail with EINTR if a signal arrives while it blocks. Careful code loops. This program copies a file and handles all three cases:

copy.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static int write_all(int fd, const char *buf, size_t n)
{
	while (n > 0) {
		ssize_t w = write(fd, buf, n);

		if (w < 0) {
			if (errno == EINTR)
				continue;
			return -1;
		}
		buf += w;
		n -= (size_t)w;
	}
	return 0;
}

int main(int argc, char **argv)
{
	char buf[65536];
	ssize_t n;
	int in, out;

	if (argc != 3) {
		fprintf(stderr, "usage: copy SRC DST\n");
		return 2;
	}
	in = open(argv[1], O_RDONLY | O_CLOEXEC);
	if (in < 0) {
		fprintf(stderr, "open %s: %s\n", argv[1], strerror(errno));
		return 1;
	}
	out = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
	if (out < 0) {
		fprintf(stderr, "open %s: %s\n", argv[2], strerror(errno));
		return 1;
	}
	while ((n = read(in, buf, sizeof(buf))) != 0) {
		if (n < 0) {
			if (errno == EINTR)
				continue;
			perror("read");
			return 1;
		}
		if (write_all(out, buf, (size_t)n) < 0) {
			perror("write");
			return 1;
		}
	}
	close(in);
	close(out);
	return 0;
}

Running strace -e trace=openat,read,write,close ./copy /etc/hostname /tmp/h shows exactly what the kernel saw:

Text
openat(AT_FDCWD, "/etc/hostname", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "/tmp/h", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644) = 4
read(3, "build-host\n", 65536)          = 11
write(4, "build-host\n", 11)            = 11
read(3, "", 65536)                      = 0
close(3)                                = 0
close(4)                                = 0

The host name is an example. Read the pattern: a read that returns 0 means end of file, not an error; the 64 KiB buffer means one call moves up to 64 KiB, which is why large buffers beat byte-at-a-time loops; and O_CLOEXEC marks the descriptor to close on exec, which stops it leaking into child programs. Setting O_CLOEXEC at open time, instead of calling fcntl afterwards, avoids a race in multithreaded programs where another thread forks between the two steps.

The modern calls worth knowing alongside these: pread and pwrite take an offset and do not move the file position, which makes them safe to share across threads; readv and writev move several buffers in one call; sendfile and copy_file_range let the kernel copy between descriptors without bouncing data through user space; and statx returns file metadata including the creation time, replacing the older stat family.

Processes: fork, exec, wait, exit

A new process is made in two steps that Unix keeps separate. fork creates a copy of the calling process, and execve replaces a process's program with a new one. Splitting them lets the parent adjust the child's environment, such as redirecting file descriptors, between the two. The parent then collects the child's exit status with wait4 or waitpid, and until it does, the finished child remains a zombie.

spawn.cc
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
	pid_t pid = fork();

	if (pid < 0) {
		perror("fork");
		return 1;
	}
	if (pid == 0) {
		execlp("echo", "echo", "child says hi", (char *)NULL);
		_exit(127);                  /* only reached if exec failed */
	}

	int status;

	waitpid(pid, &status, 0);
	printf("child exited with %d\n", WEXITSTATUS(status));
	return 0;
}
Text
child says hi
child exited with 0

The _exit(127) after execlp matters. If exec fails, the child is still a copy of the parent, and calling exit would run the parent's atexit handlers and flush its buffered output a second time. _exit skips all of that. The value 127 is the shell convention for "command not found".

Under the surface, glibc's fork calls clone with the SIGCHLD flag, and the kernel copies the page tables, not the memory: pages are shared copy-on-write and duplicated only when one side writes. vfork and posix_spawn exist for the common fork-then-exec case, avoiding even the page-table copy. For threads, clone is called with flags that share the address space, file table and signal handlers, and glibc's pthread_create uses the newer clone3. The call exit_group ends every thread in the process, while the plain exit call ends only the calling thread.

Memory: brk, mmap and friends

User-space memory comes from two system calls. brk moves the end of the data segment, which glibc's malloc uses for small allocations. mmap creates a new mapping of anonymous memory or of a file, and munmap removes it. mprotect changes the permissions of a range, and madvise gives the kernel hints about expected use. Mapping a file lets you treat it as memory, with the kernel paging it in on demand:

mapfile.cc
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

int main(void)
{
	int fd = open("/tmp/mapdemo", O_RDWR | O_CREAT | O_TRUNC, 0600);
	char *p;
	char back[6] = { 0 };

	if (fd < 0 || ftruncate(fd, 4096) < 0)
		return 1;
	p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (p == MAP_FAILED)
		return 1;

	memcpy(p, "hello", 5);              /* a plain store, no write() */
	msync(p, 4096, MS_SYNC);

	pread(fd, back, 5, 0);               /* read it back through the file */
	printf("%s\n", back);
	munmap(p, 4096);
	close(fd);
	return 0;
}
Text
hello

The store through the pointer reached the file because the mapping is MAP_SHARED. The kernel allocates the page lazily, on the first touch, and the data reaches disk later unless msync forces it. Memory is a topic deep enough for its own guide in this cluster, and the point here is that all of it rests on a handful of calls: allocation is brk or mmap, and release is munmap or a smaller brk.

Signals and time

Signals are asynchronous notifications. rt_sigaction installs a handler, rt_sigprocmask blocks delivery, kill and tgkill send them, and rt_sigreturn is how a handler returns to the interrupted code. The C library names the first two sigaction and sigprocmask. A signal can interrupt a blocked system call, which then either returns EINTR or is restarted by the kernel depending on flags, a source of enough subtle bugs that it has its own post in this cluster.

Time comes from clock_gettime, which reads a clock such as CLOCK_MONOTONIC (steady, for measuring intervals) or CLOCK_REALTIME (wall-clock). Sleeping uses nanosleep or clock_nanosleep. The interesting fact about clock_gettime is that on Linux it usually avoids the kernel entirely. The kernel maps a small shared object, the vDSO, into every process, and its functions read the time from a page the kernel keeps updated, so the call is an ordinary function call with no privilege transition. A trace of a program that reads the clock a million times shows almost none of those reads. This is the only place in the interface where "system call" is a fiction maintained for the programmer's benefit.

Sockets and waiting for many things

Network I/O uses the same descriptors. socket creates an endpoint, bind, listen, accept4 and connect set up connections, and sendto, recvfrom, sendmsg and recvmsg move data; plain read and write also work on a connected socket. A server that handles many clients needs a way to wait on all of them at once, and Linux provides poll, select and, for large numbers, epoll. Here is the smallest working demonstration, using a connected pair of sockets so the output is deterministic:

epoll_demo.cc
#include <stdio.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void)
{
	int sv[2];
	struct epoll_event ev = { .events = EPOLLIN }, out;
	int ep = epoll_create1(EPOLL_CLOEXEC);

	socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
	ev.data.fd = sv[1];
	epoll_ctl(ep, EPOLL_CTL_ADD, sv[1], &ev);

	write(sv[0], "ping", 4);

	if (epoll_wait(ep, &out, 1, 1000) == 1 && out.data.fd == sv[1]) {
		char buf[8];
		ssize_t n = read(sv[1], buf, sizeof(buf));

		printf("ready: %.*s\n", (int)n, buf);
	}
	return 0;
}
Text
ready: ping

The shape scales up: register each descriptor once with epoll_ctl, then call epoll_wait in a loop and handle whichever descriptors are reported ready. The kernel keeps the interest list, so each wait costs in proportion to the number of ready descriptors, not the number registered, which is why epoll replaced select for servers with thousands of connections. When even that is too many kernel entries, io_uring lets you queue many operations through shared memory and submit them with one call.

Directories and metadata: getdents64 and statx

Listing a directory and describing a file are separate calls, and the modern forms are worth knowing. opendir and readdir in the C library sit on getdents64, which fills a buffer with variable-length directory entries, each holding an inode number, a type hint and a name. The type hint (d_type) often saves a second call, though some file systems return DT_UNKNOWN and force you to ask. Metadata comes from the stat family, and the current member is statx, added in Linux 4.11, which lets you request only the fields you need and adds the file creation time and the mount id. glibc wraps it from 2.28:

describe.cc
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
	struct statx stx;

	if (argc != 2)
		return 2;
	if (statx(AT_FDCWD, argv[1], 0, STATX_SIZE | STATX_MODE, &stx) != 0) {
		perror("statx");
		return 1;
	}
	printf("%s: %llu bytes, %s\n", argv[1],
	       (unsigned long long)stx.stx_size,
	       S_ISREG(stx.stx_mode) ? "regular file" : "not a regular file");
	return 0;
}
Text
/etc/hostname: 11 bytes, regular file

The mask argument tells the kernel which fields you want, and the kernel reports in stx_mask which it filled. A file system that cannot supply a field leaves its bit clear, so check the mask for anything optional. The size of /etc/hostname here is an example and depends on the host name. The older stat, fstat and lstat still work, and on current glibc they are implemented with newfstatat or statx, so a trace shows the newer name.

Pipes and redirection: pipe2 and dup2

A pipe is a kernel buffer with a read end and a write end, both file descriptors. pipe2 creates one, and its flags argument can set O_CLOEXEC and O_NONBLOCK atomically. Shell pipelines are built from three calls: pipe2 to make the channel, fork to make the children, and dup2 to put the right end on standard input or standard output before exec. Doing it by hand shows how a shell works:

capture.cc
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
	int fds[2];
	char buf[64];
	ssize_t n;
	pid_t pid;

	if (pipe2(fds, O_CLOEXEC) != 0)
		return 1;
	pid = fork();
	if (pid == 0) {
		dup2(fds[1], STDOUT_FILENO);       /* stdout now feeds the pipe */
		execlp("echo", "echo", "piped", (char *)NULL);
		_exit(127);
	}
	close(fds[1]);                              /* parent keeps only the read end */
	n = read(fds[0], buf, sizeof(buf) - 1);
	buf[n > 0 ? n : 0] = '\0';
	waitpid(pid, NULL, 0);
	printf("parent read: %s", buf);
	return 0;
}
Text
parent read: piped

Two details carry the weight. The dup2 call makes descriptor 1 refer to the pipe's write end, and because the pipe's own descriptors carry O_CLOEXEC, they vanish at exec, while the duplicate on descriptor 1 does not, since dup2 clears the close-on-exec flag on its target. And the parent closes its copy of the write end: a reader sees end of file only when every write end is closed, so a forgotten write descriptor in the parent makes a later read block forever.

The catch-all calls: fcntl and ioctl

Two calls exist to avoid inventing a new system call for every small operation. fcntl manipulates a descriptor: its flags, its non-blocking mode, advisory locks and duplication with a minimum number. ioctl is the escape hatch for device-specific requests, such as asking a terminal its size, setting a serial port's speed or configuring a network interface. Each request is a number defined by the driver, with an argument whose type depends on the request.

nonblock.cc
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
	int fds[2];
	char c;
	ssize_t n;

	pipe(fds);
	fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL) | O_NONBLOCK);

	n = read(fds[0], &c, 1);                 /* nothing written yet */
	printf("read returned %zd: %s\n", n, strerror(errno));
	return 0;
}
Text
read returned -1: Resource temporarily unavailable

That error, EAGAIN (also named EWOULDBLOCK on Linux, the same value), is how a non-blocking descriptor says "no data right now, ask again later", and it is the signal that event loops built on epoll rely on. Because ioctl requests are defined per driver, they are the least portable and least discoverable part of the interface. The manual page ioctl_list and the headers under /usr/include/linux/ are the references, and a driver author is expected to document each request. Prefer a dedicated system call, a sysfs file or netlink when you design a new interface, and use ioctl where hardware or an existing driver demands it.

Synchronization and the futex

Threads need locks, and a lock that always entered the kernel would be slow. Linux's answer is the futex, "fast user-space mutex", a single system call, futex, with an operation code. The idea is that the lock itself is an integer in user memory. Taking an uncontended lock is an atomic compare-and-swap on that integer, with no kernel involvement at all. Only when the lock is contended does a thread call futex with FUTEX_WAIT, asking the kernel to put it to sleep until the integer changes, and the thread that releases the lock calls FUTEX_WAKE if there are sleepers. glibc's pthread_mutex_lock, condition variables, semaphores and pthread_join are all built on it. In a trace, a program using threads shows futex calls only where threads actually block:

Text
futex(0x7f12a8001e40, FUTEX_WAIT_PRIVATE, 2, NULL) = 0
futex(0x7f12a8001e40, FUTEX_WAKE_PRIVATE, 1) = 1

The _PRIVATE suffix means the lock is shared among threads of one process, which lets the kernel use a cheaper lookup. The same system call has operations for priority-inheriting locks (FUTEX_LOCK_PI) and, in recent kernels, for waiting on several futexes at once. This design is a good model of how the interface evolves: a hot path that must never cross the boundary is kept in user space, and the kernel is asked only to sleep and wake.

Randomness: getrandom

Programs need random bytes for keys, identifiers and hash seeds. The right source on Linux is getrandom, added in Linux 3.17 and wrapped by glibc since 2.25. It draws from the kernel's random number generator, which is seeded from hardware and system events, and it blocks only during early boot until the generator is initialized. Reading /dev/urandom also works but needs an open descriptor, which can fail in a sandbox or when descriptors run out, while getrandom is a single call with no state.

rand.cc
#include <stdio.h>
#include <sys/random.h>

int main(void)
{
	unsigned char key[16];
	ssize_t n = getrandom(key, sizeof(key), 0);

	printf("got %zd random bytes\n", n);
	return n == (ssize_t)sizeof(key) ? 0 : 1;
}
Text
got 16 random bytes

For requests of 256 bytes or less, the call does not return a short count and is not interrupted by signals once the generator is ready, so a single check of the return value is enough. The flag GRND_NONBLOCK returns EAGAIN instead of waiting during early boot, which a service starting very early should handle. Never use rand() or the time as a source for secrets.

Limits on what a process may use

The kernel enforces resource limits per process, set with setrlimit and read with getrlimit, or prlimit to change another process. Each resource has a soft limit, which the kernel enforces, and a hard limit, the ceiling to which an unprivileged process may raise its soft limit. The ones that matter most day to day are RLIMIT_NOFILE (open descriptors, often 1024 by default as a soft limit), RLIMIT_NPROC (processes per user), RLIMIT_STACK (the main thread's stack, 8 MiB by default), RLIMIT_CORE (the size of a core dump) and RLIMIT_AS (address space). A server that runs out of descriptors fails accept and open with EMFILE, and the fix is to raise the limit at startup, within the hard limit, or in the service manager's unit file. The shell's ulimit command is a front end to the same calls, and /proc/PID/limits shows the effective values for a running process. These limits are the simplest safeguard in the interface, and a process that opens a very large number of files should read its limit and budget for it instead of discovering it as an error in production.

A table of the calls you will meet most

Numbers are for x86-64 and change on other architectures, so use the SYS_ names in code:

FamilyCalls (number)
Filesread (0), write (1), close (3), lseek (8), openat (257), newfstatat (262), statx (332), getdents64 (217)
Descriptorsdup (32), pipe2 (293), fcntl (72), ioctl (16)
Memorymmap (9), mprotect (10), munmap (11), brk (12), memfd_create (319)
Processesclone (56), execve (59), exit_group (231), wait4 (61), clone3 (435)
Signalsrt_sigaction (13), rt_sigprocmask (14), kill (62), rt_sigreturn (15)
Timenanosleep (35), clock_gettime (228)
Socketssocket (41), connect (42), accept4 (288), bind (49), listen (50)
Waitingpoll (7), epoll_create1 (291), epoll_ctl (233), epoll_wait (232), io_uring_setup (425)
Synchronizationfutex (202)
Randomnessgetrandom (318)

A pattern shows in the names. A trailing at (openat, unlinkat) means "relative to a directory descriptor", which avoids path races. A 2 or 3 (pipe2, dup3, accept4) is a newer version of a call that gained a flags argument. A 64 (getdents64, pread64) marks wide offsets or structures. Prefer the newer forms, because the flags are how new features are added without breaking old programs.

Watching calls with strace and perf trace

The fastest way to understand a program is to look at the calls it makes. strace prints each call with its arguments and result, and the most useful options are -f to follow child processes, -e trace= to filter by call or group, -o to write to a file, -p to attach to a running process, -c for a summary and -T for the time spent in each call. A failing call stands out immediately:

Text
openat(AT_FDCWD, "/etc/acme/app.conf", O_RDONLY) = -1 ENOENT (No such file or directory)

That one line replaces an afternoon of guessing why a program ignores its configuration. For a hung process, attach and read the last unfinished line: it names the call and the descriptor the process waits on. strace works by stopping the target twice per call, which makes it slow, so for production use perf trace, which reads the same events from the kernel's tracepoints with far less overhead, or bpftrace for aggregation. Neither shows work done inside the program between calls, and neither shows vDSO calls.

What a call costs

A system call is more expensive than an ordinary function call because the CPU switches privilege level, the kernel saves and restores registers and switches stacks, and some processors need extra work on entry and exit as mitigations for speculative-execution attacks. The exact cost depends on the processor, the kernel configuration and the mitigations enabled, so measure on your own machine and never copy a figure from an article. What does hold everywhere is the shape of the advice:

  • Batch. One read of 64 KiB instead of 65,536 reads of one byte. writev instead of several write calls. sendmmsg and recvmmsg for many datagrams.

  • Buffer. The C library's stdio buffers do this for you, so fwrite and printf call write only when the buffer fills or flushes.

  • Avoid the call. Cache getpid-style results where safe, use the vDSO clock, and let a thread pool keep descriptors open instead of reopening files.

  • Ask for more per call. epoll returns many ready descriptors at once, and io_uring takes many requests in a single entry.

  • Let the kernel do the copy. sendfile, splice and copy_file_range move data without passing it through your buffers.

Measure before changing code, with strace -c to count calls and perf stat to see the time. A program that makes ten thousand calls a second is rarely limited by that, but one that makes ten million is.

Security: filtering what a process can call

Most programs need only a small part of the interface, and the rest is attack surface. Linux lets a process restrict itself with seccomp. In filter mode, the process installs a small program, written in classic BPF, that the kernel runs on every system call, with the call number and arguments as input. The filter returns a verdict: allow, return an error, send a signal, kill the process or notify a supervisor. Once installed, a filter cannot be removed and is inherited by children, and installing one without privilege requires first setting no_new_privs with prctl. Writing BPF by hand is tedious, so most programs use libseccomp:

lockdown.cc
#include <errno.h>
#include <seccomp.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>

int main(void)
{
	char msg[64];
	long pid;
	int len;
	scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ERRNO(EPERM));

	seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0);
	seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);
	seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigreturn), 0);
	if (seccomp_load(ctx) != 0)
		return 1;

	pid = syscall(SYS_getpid);          /* not on the allow list */
	len = snprintf(msg, sizeof(msg), "getpid returned %ld: %s\n",
		       pid, strerror(errno));
	write(1, msg, (size_t)len);
	_exit(0);
}
Text
getpid returned -1: Operation not permitted

Compile it with -lseccomp. The filter starts from a default of "fail with EPERM" and allows only three calls. Every other call, including the getpid here, returns an error without reaching the kernel's implementation. The output goes through write directly rather than printf because stdio may call other system calls the filter would refuse. Real profiles, such as the ones Docker, systemd and browsers ship, list a few hundred allowed calls and handle architecture checks, since a filter that compares only call numbers can be fooled by a 32-bit caller whose numbers mean something else.

Seccomp is one layer. Capabilities divide root's power into pieces a process can drop, namespaces give a process its own view of mounts, processes and networks, and ptrace restrictions control who can inspect whom. Together they let a process be given exactly the authority it needs.

Compatibility and probing for new calls

The kernel keeps one promise above almost all others: it does not break programs that use the system call interface. A call introduced years ago behaves the same today, and a number is never reused. That stability makes it safe to ship a binary built against old headers, and the opposite problem more interesting: a program built against new headers may run on an older kernel that lacks a call.

An unknown call number returns ENOSYS, and a sandbox may answer a blocked call with EPERM instead. So code that wants a newer feature tries it and falls back on those two errors, caching the answer so the failing call is paid for once. It does not compare the kernel version string, because distribution kernels backport features and containers filter calls independently of the kernel. The same technique handles new flags on old calls: an old kernel returns EINVAL for a flag it does not know, and the program retries without it. A companion post in this cluster builds the probe in full for close_range.

Adding a call to the kernel

You will rarely add a system call, and the kernel community accepts new ones reluctantly, because each is permanent. The mechanics are instructive anyway. A new call needs a line in the architecture's table (syscall_64.tbl on x86-64), a prototype in include/linux/syscalls.h, a body written with the SYSCALL_DEFINEn macros, and a build rule. The macro generates a wrapper that widens every argument to long, casts it back to its declared type, records metadata for tracing and, on x86-64, builds an entry that reads its arguments from the saved registers. Inside the body, never dereference a user pointer directly: use copy_from_user, copy_to_user and strncpy_from_user, which validate the address and survive a fault. A well-designed new call takes a flags argument that must be zero today and rejects unknown bits, so the call can grow later. The kernel documentation file Documentation/process/adding-syscalls.rst lists the rules, and two posts in this cluster walk through adding a call and expanding its macros.

A program with no C library

To see that nothing more than the instruction is involved, here is a complete program that never touches libc. It defines its own entry point and issues two calls:

nolibc.cc
static long sys3(long n, long a, long b, long c)
{
	long r;

	__asm__ volatile ("syscall"
			  : "=a"(r)
			  : "a"(n), "D"(a), "S"(b), "d"(c)
			  : "rcx", "r11", "memory");
	return r;
}

void _start(void)
{
	sys3(1, 1, (long)"no libc here\n", 13);   /* write(1, ..., 13) */
	sys3(231, 0, 0, 0);                       /* exit_group(0) */
	for (;;)
		;
}
Shell
gcc -O2 -static -nostdlib -fno-stack-protector -o nolibc nolibc.c
./nolibc
Text
no libc here

The binary is a few kilobytes, with no dynamic loader, no startup code and no main. The kernel loads it and jumps to _start, which is the real entry point of every program; glibc's own _start sets up the C environment and calls main. The for (;;) is there because exit_group never returns, and the compiler needs _start not to fall off the end. Go's runtime and many tiny container tools work this way, with a system call layer written per architecture.

System calls inside containers and virtual machines

A containerized process makes the same calls as any other, and they reach the same host kernel: a container is a group of processes with restricted views, not a separate kernel. That shapes what you observe. Namespaces change what a call returns, so getpid reports a process id from the container's own numbering, and mount or sethostname affect only the container's view. Control groups limit what a process may consume, so a call can fail with ENOMEM or EMFILE at a limit that is far below the machine's capacity. And the runtime installs a seccomp filter that rejects calls the profile does not list, which is why a program that works on a laptop can fail inside a container with EPERM on a call such as ptrace or mount. When that happens, strace inside the container, if the profile allows it, names the call, and the runtime's documentation lists the default allowed set.

A virtual machine is different. It runs its own kernel, so system calls from its programs never leave the guest, and the hypervisor sees only the traps that the guest kernel causes, such as privileged instructions and device access. Programs in a guest pay the same entry cost as on bare metal, and the guest kernel's own hardware requests are what the hypervisor must intercept or emulate. Sandboxed runtimes that implement the interface in user space, such as gVisor, sit in between: they intercept each system call and reimplement it, which gives strong isolation at the cost of speed for call-heavy programs. If you debug a performance gap between environments, count calls with strace -c first, because the same program can make the same calls and pay very different prices for them.

Mistakes that recur

A short catalogue of the errors this interface invites, with the habit that prevents each:

MistakeSymptomHabit
Assuming write writes everythingTruncated output on pipes and socketsLoop until all bytes are written
Ignoring EINTRRandom failures when signals arriveRetry, or install handlers with SA_RESTART where it applies
Retrying close after EINTRClosing another thread's new descriptorTreat EINTR from close as success on Linux
Leaking descriptors into childrenSockets stay open after execUse O_CLOEXEC, SOCK_CLOEXEC, EPOLL_CLOEXEC
Reading errno lateWrong error reportedSave errno immediately after the failing call
Hard-coding numbersBreaks on ARM64 and RISC-VUse SYS_ constants from <sys/syscall.h>
Path racesTime-of-check to time-of-use bugsUse the *at calls with a directory descriptor
Trusting a version stringFails on backported or filtered kernelsProbe by calling and handling ENOSYS
Calling fork in a threaded program, then doing more than execDeadlocks in the childCall only async-signal-safe functions after fork

When not to call the kernel directly

The wrapper is the right default. A raw call forfeits errno translation, cancellation points, the library's fallbacks and type checking, and it ties the code to one architecture's numbers. Use syscall() only when no wrapper exists, and wrap it in a function with a real prototype so the rest of the code is checked. Use a higher-level interface whenever one fits: stdio instead of read and write for text, posix_spawn instead of hand-written fork and exec, an event library instead of raw epoll if you do not need its control. Programs in other languages go through the same calls under different names, and the same tools, strace above all, reveal them.

A learning path

Work through the interface in this order. Start with file descriptors and the five calls open, read, write, lseek and close, and write the copy program above from memory. Then trace small programs with strace until the preamble of a dynamically linked process stops looking strange. Learn the error convention thoroughly, including EINTR and short counts. Move to processes and signals, then to mmap and the memory calls, then to sockets and epoll. After that, read the kernel side: the table, the entry code and one simple call such as getpid. Finish with the security tools, seccomp and capabilities. At each step, the manual page, strace and the kernel source are the three references, and they agree.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.