Linux System Programming · intermediate · ~8 min

errno and error reporting

Diagnose syscall failures.

Lesson

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.

Code examples

int fd = open(path, O_RDONLY);
if (fd < 0) {
    fprintf(stderr, "open %s: %s\n", path, strerror(errno));
    return 1;
}

Common mistakes

  • Reading errno after printfprintf itself may have set it.