System calls & error handling
Call system calls correctly and handle every failure using errno.
By Invicly Tech, , in Linux System Programming. About 9 minutes to read.
In short
A system call switches the CPU from user mode into the kernel, runs a kernel function and returns a result. Most calls return -1 on failure and set the thread-local errno to explain why. Robust programs check every return value and handle cases like EINTR and short reads.
Explained simply
A system call is how your program asks the kernel for help. Open this file. Read 100 bytes. Start a new process. Each one has a number, and your program passes that number and some arguments to the kernel.
System calls can fail for many normal reasons: the file does not exist, you lack permission, the disk is full. Most calls tell you about failure by returning -1. A global-looking variable called errno then holds a code that says why.
Beginners often skip the checks because the code works on their machine. Then it runs on a server with a missing directory and silently does the wrong thing. Checking every return value is the single most important habit in system programming.
There are also two surprises to learn: a call can be interrupted by a signal (EINTR), and read or write can move fewer bytes than you asked for. Both are normal, and both are easy to handle once you know.
Press Play on a diagram to walk through it one step at a time.
- Program to glibc: read(fd, buf, n)1read(fd, buf, n)
- glibc to Kernel: syscall instruction, number and args in registers2syscall instruction, number and args in registers
- Kernel to glibc: bytes read, or a negative error code3bytes read, or a negative error code
- glibc to Program: return n, or -1 with errno set4return n, or -1 with errno set
- 1Call
n = write(fd, p, left);
- 2Failed?
n == -1: check errno
- 3EINTR
Retry the same call
- 4Other error
Report with perror and stop
- 5Short success
p += n; left -= n; loop until left == 0
In depth
How errno works
errno is an int that the C library sets when a call fails. It is per thread, so threads do not overwrite each other's errors. Its values have names like ENOENT (no such file), EACCES (permission denied) and EAGAIN (try again later), defined in errno.h.
Three rules keep you safe. Only read errno right after a call has reported failure, because successful calls may leave old values in it. Save it to a local variable before calling anything else, because even printf can change it. And use strerror(errno) or perror("open") to turn the number into a readable message.
- Check the return value first, then errno
- Save errno immediately: int saved = errno;
- perror prefixes your text to the error message
Return value conventions
Most system calls return -1 on failure and something useful on success: a file descriptor, a byte count, a process ID. A few are different, and the man page RETURN VALUE section always tells you.
mmap returns MAP_FAILED, not NULL. The pthread functions do not use errno at all; they return the error number directly and 0 on success. getpriority can legally return -1 on success, so you must set errno = 0 before the call and check it afterwards. Library functions like fopen return NULL on failure. When in doubt, read the man page section called RETURN VALUE.
- Most syscalls: -1 and errno
- mmap: MAP_FAILED
- pthreads: return the error code directly
- stdio: NULL or EOF
EINTR: interrupted by a signal
Some calls can wait a long time: reading from a terminal or a socket, waiting for a child. If a signal arrives during that wait and your program has a handler for it, the kernel runs the handler and then the call may return -1 with errno set to EINTR. Nothing is broken; the call just did not finish.
The usual fix is to retry in a loop while errno == EINTR. Alternatively, install handlers with the SA_RESTART flag so the kernel restarts most calls automatically. Some calls, like poll and nanosleep, are never restarted and always need handling.
- Program to Kernel: read(fd, ...) waits for data1read(fd, ...) waits for data
- Kernel to Signal handler: Signal arrives: run the handler2Signal arrives: run the handler
- Signal handler to Kernel: Handler returns3Handler returns
- Kernel to Program: -1, errno = EINTR4-1, errno = EINTR
- Program to Kernel: Retry read5Retry read
- Kernel to Program: Bytes read6Bytes read
Partial results
read(fd, buf, 4096) promises to read at most 4096 bytes, not exactly 4096. From a pipe or socket it returns whatever has arrived so far. From a file near the end it returns what is left, and 0 means end of file.
write can also be short, especially on sockets and pipes when buffers fill up. So correct code always loops: keep calling write with the remaining bytes until all are sent. Forgetting this works fine in tests with small files, then corrupts data under load.
- read returning 0 means end of file
- A short read or write is not an error
- Loop until all bytes are moved
- Step 1write(fd, buf, 10000)
Returns 4096: a short write
- Step 2Advance
buf += 4096, 5904 bytes left
- Step 3write again
Returns 5904
- Step 4Done
Loop ends when 0 bytes are left
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Trace a syscall from wrapper to kernel~45m
- 2Check return values on every call~45m
- 3Report errors with errno and perror~45m
- 4Handle EINTR and partial results~45m
Key points
- Check every return value; -1 means failure for most calls.
- errno is only meaningful right after a call has failed.
- EINTR means a signal interrupted the call; usually you retry it.
- System calls cost far more than function calls, so batch work where possible.
Key terms
Tap a card to flip it. 0/6 known
Examples
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void) {
int fd = open("/etc/shadow", O_RDONLY);
if (fd == -1) {
fprintf(stderr, "open: %s (errno %d)\n", strerror(errno), errno);
return 1;
}
close(fd);
return 0;
}As a normal user this prints: open: Permission denied (errno 13).
A write_all helper you can reuse everywhere
This helper writes every byte of a buffer or reports a real error. Each call moves the pointer forward by what was actually written. EINTR simply restarts the loop. Any other error returns -1 with errno still set, so the caller can print it. You will use this pattern again for sockets and pipes.
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
static int write_all(int fd, const char *p, size_t left) {
while (left > 0) {
ssize_t n = write(fd, p, left);
if (n == -1) { if (errno == EINTR) continue; return -1; }
p += n; left -= (size_t)n;
}
return 0;
}
int main(void) {
if (write_all(STDOUT_FILENO, "hello\n", 6) == -1) { perror("write"); return 1; }
return 0;
}Reporting errors usefully
A good error message says what was attempted, on what, and why it failed. Here we try to create a file in a directory that may not exist. We save errno before printing, then branch on it so a missing directory and a permission problem get different advice. Run it with a path like /nope/x.txt and then /root/x.txt.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
const char *path = argc > 1 ? argv[1] : "/nope/x.txt";
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
int e = errno;
fprintf(stderr, "cannot create %s: %s\n", path, strerror(e));
if (e == ENOENT) fprintf(stderr, "hint: create the directory first\n");
return 1;
}
close(fd); return 0; }Quick reference
- if (call(...) == -1) { perror("call"); ... }
- Save errno at once: int e = errno;
- strerror(e) turns a code into text; errno -l lists them (moreutils)
- EINTR: retry, or use SA_RESTART on the handler
- read == 0 means end of file, not an error
- Loop on read and write until all bytes are moved
- pthread_* return the error number instead of setting errno
- Read the RETURN VALUE and ERRORS sections of each man page
Common mistakes
- Reading errno after a successful call and trusting its value.
- Calling another function such as printf before saving errno.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a program that tries to open a path given on the command line and prints either "ok" or the error using perror.
- Exercise 2medium
Write ssize_t read_full(int fd, char *buf, size_t n) that keeps reading until n bytes arrive or end of file, retrying on EINTR. Return the bytes read or -1.
- Exercise 3hard
Call a raw system call without the glibc wrapper: use syscall(SYS_getpid) and syscall(SYS_write, ...) and compare the results with getpid().
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How many system calls does Linux have?
- Around 450 on x86-64, though a typical program uses only a few dozen. man 2 syscalls lists them all.
- Is errno a global variable?
- It behaves like one, but in modern glibc it is a macro that reads a per-thread value. Each thread has its own errno, so threads do not clobber each other's errors.
- Should I exit on every error?
- Not always. Exiting is fine for small tools, but servers should report the error, clean up that one request or connection, and keep running.