Error Handling

The errno Variable

On error, system calls (and most C library functions) return -1 and set the global variable errno.

Error handling with system calls
ssize_t n = read(fd, buffer, sizeof(buffer));
if (n == -1)
    if (errno == EINTR) {
        /* interrupted system call, retry possible */
    else {
        /* abort, reporting the error */

errno Is A Global Variable

Where’s the bug?

Bad Error Handling
ssize_t n = read(fd, buffer, sizeof(buffer));
if (n == -1) {
    fprintf(stderr, "Error %d\n", errno);
    if (errno == EINTR)
        /* ... */

Helper Functions




void perror(const char *s)

Message to stderr, beginning with s

man -s 3 perror

char *strerror(int errnum)

Modifiable pointer to error description

man -s 3 strerror

char *strerror_r(int errnum, char *buf, size_t buflen)

Cleanest alternative: _r ⟶ “reentrant” (thread safe)

man -s 3 strerror_r

Error output
if (n == -1)