Check Return Values of System Calls the Right Way
Check every system call result in C: the -1 convention, short reads and writes, EINTR retries and close errors, with working helpers for Linux and glibc 2.41.

Most system-call bugs are not exotic. They are unchecked return values: a write that wrote half the buffer, a read that returned zero, a close whose failure nobody saw. The rules for checking are small, and once you know them you apply the same few patterns to every call. This post goes through them with C11 and POSIX.1-2024 on Linux with glibc 2.41. Each rule comes from the specification of the call, for example the POSIX page for write, and the broader context is the complete guide to error handling in this cluster. The previous posts explained errno and how to print it.
Know the failure signal of each call
There is no single convention, so the first step is to read the RETURN VALUE section of the man page. The common patterns are these.
| Call | Success | Failure |
|---|---|---|
open, socket, dup | a non-negative file descriptor | -1 |
read | bytes read; 0 at end of file | -1 |
write | bytes written, possibly fewer than requested | -1 |
close, unlink, mkdir | 0 | -1 |
mmap | the mapped address | MAP_FAILED, which is (void *)-1 |
malloc, fopen | a pointer | NULL |
pthread_mutex_lock | 0 | a positive error number, not -1 |
Notice that mmap does not return NULL on failure. A program that tests if (!p) after mmap never notices the failure and then crashes on the first access. Notice too that read returning 0 is not an error: it means the end of the file, or on a socket, that the peer closed the connection.
A shortcut that is almost always right for the first group is to compare against -1 and not to test < 0, because the documented failure value is exactly -1. For calls that return a count, such as read and write, < 0 and == -1 are equivalent in practice, so pick one style and stay with it across the code base.
Handle short reads and writes
A write of 100 bytes may return 60. The call succeeded, in the sense that it did not fail, but you still have 40 bytes to send. This happens with pipes, sockets and terminals, and with regular files when the disk is full or a signal interrupts the call. Code that ignores the return count loses data silently.
The standard fix is a loop that keeps going until everything is written or a real error occurs.
#include <errno.h>
#include <stddef.h>
#include <unistd.h>
/* Returns 0 when all bytes were written, -1 on error with errno set. */
int write_all(int fd, const void *buf, size_t len)
{
const char *p = buf;
while (len > 0) {
ssize_t n = write(fd, p, len);
if (n == -1) {
if (errno == EINTR)
continue; /* interrupted before any data moved */
return -1;
}
p += n;
len -= (size_t)n;
}
return 0;
}The loop does two things. It advances the pointer by the number of bytes actually written, and it retries only on EINTR. A write that returns 0 for a non-zero request is not expected for regular files, but the loop would spin forever if it happened, so treat it as an error in code that must be strict.
A matching helper for read has a different goal. You usually want to read until you have len bytes or the stream ends, and the caller needs to tell those two outcomes apart.
#include <errno.h>
#include <stddef.h>
#include <unistd.h>
/* Returns the number of bytes read (less than len only at end of file),
or -1 on error with errno set. */
ssize_t read_all(int fd, void *buf, size_t len)
{
char *p = buf;
size_t done = 0;
while (done < len) {
ssize_t n = read(fd, p + done, len - done);
if (n == -1) {
if (errno == EINTR)
continue;
return -1;
}
if (n == 0)
break; /* end of file */
done += (size_t)n;
}
return (ssize_t)done;
}Reading a 10-byte file with a 16-byte request returns 10, not an error, and the caller knows it reached the end because the count is smaller than requested.
Retry on EINTR, but only where it applies
EINTR means a signal handler ran while the call was blocked, and the call returned early. Whether you see it depends on how signal handlers were installed. If a handler is installed with sigaction and the SA_RESTART flag, the kernel restarts many calls automatically. Without that flag, or for calls that are never restarted such as poll, select and epoll_wait, you get EINTR and must decide. For read, write, open and accept, retrying is the usual right answer.
Note the exception for close. After close returns EINTR, the state of the descriptor is unspecified in POSIX. On Linux the descriptor is closed regardless, so retrying risks closing a descriptor that another thread has just been given. Do not retry close on Linux.
Check close
Beginners skip checking close because there is nothing left to do with the descriptor. That is a mistake for files you wrote. On network filesystems and on some local ones, data can be buffered, and the error from a failed write-back, for example ENOSPC or EIO, is reported at close time, not at write time. A program that writes a file and ignores close can report success while the file is truncated.
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int write_all(int fd, const void *buf, size_t len);
int save(const char *path, const char *text)
{
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror(path);
return -1;
}
if (write_all(fd, text, strlen(text)) == -1) {
perror("write");
close(fd);
return -1;
}
if (close(fd) == -1) {
perror("close");
return -1;
}
return 0;
}For data that must survive a power loss, add fsync(fd) before close and check it too. close alone does not guarantee that the data reached the disk.
Do not hide checks behind macros that ignore them
Compilers can help. glibc marks some functions with __attribute__((warn_unused_result)) when _FORTIFY_SOURCE is enabled, so cc -O2 -D_FORTIFY_SOURCE=2 -Wall warns about an ignored write or read result. Casting the result to void to silence the warning is a decision to ignore the failure, and it should come with a comment that says why. A good place for that is a best-effort write to a log file during shutdown, where nothing more can be done about a failure anyway.
For code that needs to check dozens of calls, a small macro keeps the checks short without hiding them.
#include <stdio.h>
#include <stdlib.h>
#define CHECK(expr) \
do { \
if ((expr) == -1) { \
perror(#expr); \
exit(1); \
} \
} while (0)With this, CHECK(mkdir("out", 0755)); on a read-only filesystem prints mkdir("out", 0755): Read-only file system and exits. The macro suits small tools and tests. In libraries, return the error instead of exiting.
Testing the failure paths
Error handling code is the code that runs least, so it is the code most likely to be wrong. You can exercise it without special hardware by arranging for the call to fail. To test the open branch, pass a path that does not exist. To test write failures, open /dev/full, a device that accepts opens and fails every write with ENOSPC. To test read errors, read from a descriptor you have already closed, which gives EBADF. To test short writes, write to a pipe whose reader is slow, or set a small SO_SNDBUF on a socket and write more than fits.
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int write_all(int fd, const void *buf, size_t len);
int main(void)
{
int fd = open("/dev/full", O_WRONLY);
if (fd == -1) {
perror("open /dev/full");
return 1;
}
if (write_all(fd, "hello", 5) == -1) {
perror("write /dev/full");
return 2;
}
return 0;
}write /dev/full: No space left on deviceThis is a cheap and repeatable test that your program notices a full disk and reports it, and that the exit status tells the caller something went wrong. A program whose main returns zero after that failure has a bug that a real full disk would expose at the worst moment. The same idea applies to every checked call: pick the cheapest way to make it fail, run the program, and look at both the message and the exit status.
Choosing the reaction
Checking is only half the job; the other half is deciding what to do. There are three honest reactions to a failed call. Retry, for transient conditions such as EINTR. Recover, by using a fallback, such as creating a missing directory and trying again once. Or fail, by returning the error up the call chain to a place that knows enough to report it. A fourth reaction, ignoring the error, belongs only to best-effort operations, and a comment should say so. Mixing up these reactions is how programs end up retrying a permission error forever or aborting on a signal.


