Linux System Programming · intermediate · ~8 min
Diagnose syscall failures.
POSIX functions report failures by returning -1 (or NULL) and setting the global errno. perror("context") prints context: <human-readable error> to stderr; strerror(errno) returns the message string.
errno is thread-local in modern systems — but it can be overwritten by the very next library call, so save it immediately if you need to use it later.
int fd = open(path, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "open %s: %s\n", path, strerror(errno));
return 1;
}
errno after printf — printf itself may have set it.