A program running in user mode cannot open a file or send a packet on its own. It asks the kernel with a system call, the defined interface between user space and the kernel.
From function to kernel
Most programs do not invoke system calls by hand. They call functions in the C library, such as read() or write(), and the library does the low level step. That step places a call number and arguments where the kernel expects them, then runs a special instruction (syscall on x86-64) that switches to kernel mode. Call numbers differ between architectures.
Not every library function is a system call. strlen() works entirely in user space, and printf() usually collects text in a buffer first, and the library calls write later.
Common calls
openatopens a file and returns a file descriptor, a small number.readandwritemove data through a descriptor.closereleases it.clone(orfork) creates a new process.execvereplaces the current program with another.
Their manual pages are in section 2, for example man 2 read. The list is in syscalls(2).
Trace them with strace
strace shows the system calls a program makes. You may need to install it.
echo hi > note.txt
strace -e trace=openat,read,write,close cat note.txtopenat(AT_FDCWD, "note.txt", O_RDONLY) = 3
read(3, "hi\n", 131072) = 3
write(1, "hi\n", 3) = 3
read(3, "", 131072) = 0
close(3) = 0This is shortened: library loading appears first, and some versions of cat copy with a different call, so you may not see these exact lines.
Read a line as name, arguments, then result after =. Descriptor 1 is standard output. A read that returns 0 means end of file.
Errors
A failed call shows -1 and an error name:
strace -e trace=openat cat missing.txtopenat(AT_FDCWD, "missing.txt", O_RDONLY) = -1 ENOENT (No such file or directory)The C library stores that error code in errno, and the program usually turns it into a message. EACCES means permission denied.
Useful options
strace -ffollows child processes.strace -cprints a summary table of calls, errors and time.strace -o trace.txtwrites the output to a file.strace -p PIDattaches to a running process, which often needs root.
Tracing slows a program, and its output can contain passwords or other private data.
For more on file descriptors and redirection, use the streams and text lab.
Try it
- Run
strace -c lsand find the most frequent call. - Run
strace -e trace=execve sh -c 'ls; ls'and see which programs start. Add-fand compare. - Trace
caton a file that does not exist and find the error name.
Check your understanding
System calls
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.