Skip to content

errno

Purpose

errno stores the error code set by many failing C library and system call wrappers.

It should be checked immediately after a function returns an error indication, such as -1.

#include <errno.h>
#include <string.h>
#include <stdio.h>

Minimal Example

ssize_t n = read(fd, buf, sizeof(buf));
if (n < 0) {
    if (errno == EINTR)
        return 0;

    fprintf(stderr, "read failed: %s
", strerror(errno));
    return -1;
}

Common Error Codes

Error Meaning
EINTR Interrupted by signal. Retry may be appropriate.
EAGAIN / EWOULDBLOCK Operation would block on a non-blocking fd.
EINVAL Invalid argument or unsupported configuration.
ENOSPC No space left or queue/buffer full.
EBADF Invalid file descriptor.

Common Pitfalls

  • Reading errno when the function did not fail.
  • Calling another library function before saving errno.
  • Returning -errno after errno may have changed.