Dr. Roger Ianjamasimanana

The errno.h header in C programming

By Dr. Roger Ianjamasimanana

1. What is errno?

In C programming, errno.h is the header file that you include in your source code to access the errno variable and its predefined error macros such as ENOENT, EACCES, etc. The errno variable itself is a global integer that is set by certain system calls and library functions when an error occurs, indicating the specific error that took place.

The errno variable is thread-local in most modern C libraries, so its value is unique per thread rather than shared globally across all threads.

2. List of common errors and macros

errno.h defines a set of macros, each representing a unique error code. Below is a unified list of errno error codes, including some that may not be present on all systems or that are platform-specific (e.g., GNU/Hurd, Linux, BSD, etc.). The descriptions give an overview of each error’s meaning. Always refer to your platform’s documentation for exact usage and numeric values.

Error code Meaning / Summary
EPERM “Operation not permitted.” Typically indicates a lack of the required privileges or ownership to perform an operation.
ENOENT “No such file or directory.” A referenced file does not exist in a context where it’s expected to exist.
ESRCH “No such process.” No process matches the specified process ID.
EINTR “Interrupted system call.” A signal interrupted an in-progress system call. Often retrying may be necessary unless the call auto-restarts.
EIO “Input/output error.” A physical I/O error occurred, e.g., read/write error on a device.
ENXIO “No such device or address.” Indicates a missing device file or a misconfigured/missing physical device.
E2BIG “Argument list too long.” The arguments to an exec call exceed system limits.
ENOEXEC “Exec format error.” The target file for exec is not a valid executable.
EBADF “Bad file descriptor.” Often indicates using an invalid descriptor or performing invalid operations (e.g., writing to a read-only descriptor).
ECHILD “No child processes.” No existing child process for wait-like operations.
EDEADLK “Resource deadlock avoided.” The system detected a potential deadlock (e.g., with file or thread locks).
ENOMEM “Cannot allocate memory.” The system cannot provide more virtual memory or address space.
EACCES “Permission denied.” File or resource permissions prohibit the requested operation.
EFAULT “Bad address.” An invalid pointer or address was supplied to a system call.
ENOTBLK “Block device required.” Indicates a situation where a non-block device is used but a block device is expected.
EBUSY “Device or resource busy.” The requested resource cannot be used because it’s already in exclusive use.
EEXIST “File exists.” Occurs when creating a file or directory that already exists.
EXDEV “Invalid cross-device link.” Attempt to link or rename files across different filesystems.
ENODEV “No such device.” The wrong type of device was passed to a function or the device is unavailable.
ENOTDIR “Not a directory.” A non-directory file was used in a context requiring a directory.
EISDIR “Is a directory.” Attempted an operation on a directory where it should be a regular file.
EINVAL “Invalid argument.” Passed an unacceptable argument to a system call or library function.
EMFILE “Too many open files.” The current process has hit its open file descriptor limit.
ENFILE “Too many open files in system.” The system-wide limit of file descriptors is reached.
ENOTTY “Inappropriate ioctl for device.” Attempted an I/O control operation on an invalid device type.
ETXTBSY “Text file busy.” Trying to write to or execute a file that’s open for writing or currently executed.
EFBIG “File too large.” Exceeds the maximum file size allowed by the system.
ENOSPC “No space left on device.” The device (disk) is full, so a write can’t proceed.
ESPIPE “Illegal seek.” Seeking on a file descriptor that doesn’t support it (e.g., pipe or socket).
EROFS “Read-only file system.” Attempted to modify data on a read-only filesystem.
EMLINK “Too many links.” The link count of a file is at maximum; can’t create another link.
EPIPE “Broken pipe.” Writing to a pipe or socket with no reader; typically raises SIGPIPE unless handled.
EDOM “Numerical argument out of domain.” Invalid argument to a math function (e.g., sqrt(-1)).
ERANGE “Numerical result out of range.” Overflow or underflow in a math function.
EAGAIN / EWOULDBLOCK “Resource temporarily unavailable.” Often for non-blocking I/O that would block, or a temporary resource shortage. In many implementations, EWOULDBLOCK is the same value as EAGAIN.
EINPROGRESS “Operation now in progress.” Non-blocking connect or similar operation in progress.
EALREADY “Operation already in progress.” Another operation is already ongoing for this object.
ENOTSOCK “Socket operation on non-socket.” A file descriptor references a non-socket, but a socket operation was attempted.
EMSGSIZE “Message too long.” A message sent on a socket was larger than the supported maximum.
EPROTOTYPE “Protocol wrong type for socket.” The chosen protocol is incompatible with the socket type.
ENOPROTOOPT “Protocol not available.” Specified socket option is invalid for this protocol.
EPROTONOSUPPORT “Protocol not supported.” The system doesn’t support the requested protocol in the socket domain.
ESOCKTNOSUPPORT “Socket type not supported.” The requested type of socket is unsupported.
EOPNOTSUPP “Operation not supported.” The requested operation isn’t implemented for the object or protocol.
EPFNOSUPPORT “Protocol family not supported.” The desired protocol family is unsupported.
EAFNOSUPPORT “Address family not supported by protocol.” The address family does not match the protocol.
EADDRINUSE “Address already in use.” Attempting to bind a socket to an address that’s already bound.
EADDRNOTAVAIL “Cannot assign requested address.” The requested address is not local, or otherwise unavailable.
ENETDOWN “Network is down.” A socket operation failed because the local network is down.
ENETUNREACH “Network is unreachable.” No route to the target network address.
ENETRESET “Network dropped connection on reset.” The local system aborted the connection.
ECONNABORTED “Software caused connection abort.” Typically a local network subsystem abort.
ECONNRESET “Connection reset by peer.” The remote side closed the connection unexpectedly.
ENOBUFS “No buffer space available.” System memory for socket buffers is exhausted.
EISCONN “Transport endpoint is already connected.” The socket is already connected.
ENOTCONN “Transport endpoint is not connected.” Socket operation requires a connection, but none is established.
EDESTADDRREQ “Destination address required.” A datagram socket send was issued without specifying an address.
ESHUTDOWN “Cannot send after transport endpoint shutdown.” The socket is shut down for writing/reading.
ETOOMANYREFS “Too many references: cannot splice.” Rare error indicating excessive references in a spliced network path.
ETIMEDOUT “Connection timed out.” Remote host didn’t respond within the allotted time.
ECONNREFUSED “Connection refused.” No service is listening at the remote address, or it actively refused.
ELOOP “Too many levels of symbolic links.” A path lookup encountered a symbolic link loop.
ENAMETOOLONG “File name too long.” Exceeds PATH_MAX or other naming limits.
EHOSTDOWN “Host is down.” The remote machine is unreachable because it’s down.
EHOSTUNREACH “No route to host.” Routing failed; the remote host is unreachable.
ENOTEMPTY “Directory not empty.” Attempted to remove or rename a directory that still contains files.
EPROCLIM “Too many processes.” The per-user or system limit on processes has been reached.
EUSERS “Too many users.” Some file quota or system resource for users is exhausted.
EDQUOT “Disk quota exceeded.” The user’s or group’s disk quota was exceeded.
ESTALE “Stale file handle.” Common in NFS or other network file systems when the file handle is invalid.
EREMOTE “Object is remote.” Attempt to perform a local operation on a remote file object (rare or system-specific).
EBADRPC “RPC struct is bad.” A remote procedure call structure is malformed.
ERPCMISMATCH “RPC version wrong.” The remote procedure call version is not compatible.
EPROGUNAVAIL “RPC program not available.” The remote server does not have the desired RPC program.
EPROGMISMATCH “RPC program version wrong.” The RPC server program version does not match the requested version.
EPROCUNAVAIL “RPC bad procedure for program.” The procedure within the RPC program is invalid or unimplemented.
ENOLCK “No locks available.” The system can’t allocate another file lock resource.
EFTYPE “Inappropriate file type or format.” The file type or format is not correct for the requested operation.
EAUTH “Authentication error.” A security or authentication check failed.
ENEEDAUTH “Need authenticator.” Additional authentication data is required.
ENOSYS “Function not implemented.” The operating system or C library does not implement this function.
ELIBEXEC “Cannot exec a shared library directly.” Attempted to run a shared library as an executable.
ENOTSUP “Not supported.” Valid parameters were given, but the feature is not available for this object.
EILSEQ “Invalid or incomplete multibyte or wide character.” Encountered a bad character sequence.
EBADMSG “Bad message.” An IPC or network message is corrupted or malformed.
EIDRM “Identifier removed.” An IPC resource (e.g., SysV message queue) was removed while in use.
EMULTIHOP “Multihop attempted.” A multi-hop link was attempted but not supported.
ENODATA “No data available.” Sometimes used instead of EOF or for certain IPC operations.
ENOLINK “Link has been severed.” In remote file systems or similar, indicates a severed link.
ENOMSG “No message of desired type.” In message queue operations, indicates no suitable message.
ENOSR “Out of streams resources.” A System V STREAMS–related resource shortage.
ENOSTR “Device not a stream.” Attempted a STREAMS-specific operation on a non-STREAMS device.
EOVERFLOW “Value too large for defined data type.” E.g., reading file size into too small a variable.
EPROTO “Protocol error.” A serious error in a communications protocol occurred.
ETIME “Timer expired.” A blocking I/O or IPC operation timed out (some systems use ETIMEDOUT similarly).
ECANCELED “Operation canceled.” An asynchronous operation was canceled before completion.
EOWNERDEAD “Owner died.” A robust mutex’s owner terminated without unlocking, requiring recovery.
ENOTRECOVERABLE “State not recoverable.” The system or library cannot restore a consistent state after a crash.
ERESTART “Interrupted system call should be restarted.” (Linux/i386 kernel internal error code.)
ECHRNG “Channel number out of range.” (Linux/i386 kernel specific.)
EL2NSYNC “Level 2 not synchronized.” (Linux/i386 kernel specific.)
EL3HLT “Level 3 halted.” (Linux/i386 kernel specific.)
EL3RST “Level 3 reset.” (Linux/i386 kernel specific.)
ELNRNG “Link number out of range.” (Linux/i386 kernel specific.)
EUNATCH “Protocol driver not attached.” (Linux/i386 kernel specific.)
ENOCSI “No CSI structure available.” (Linux/i386 kernel specific.)
EL2HLT “Level 2 halted.” (Linux/i386 kernel specific.)
EBADE “Invalid exchange.” (Linux/i386 kernel specific.)
EBADR “Invalid request descriptor.” (Linux/i386 kernel specific.)
EXFULL “Exchange full.” (Linux/i386 kernel specific.)
ENOANO “No anode.” (Linux/i386 kernel specific.)
EBADRQC “Invalid request code.” (Linux/i386 kernel specific.)
EBADSLT “Invalid slot.” (Linux/i386 kernel specific.)
EDEADLOCK “File locking deadlock error.” Another name for EDEADLK.
EBFONT “Bad font file format.” (Linux/i386 kernel specific.)
ENONET “Machine is not on the network.” (Linux/i386 kernel specific.)
ENOPKG “Package not installed.” (Linux/i386 kernel specific.)
EADV “Advertise error.” (Linux/i386 kernel specific.)
ESRMNT “Srmount error.” (Linux/i386 kernel specific.)
ECOMM “Communication error on send.” (Linux/i386 kernel specific.)
EDOTDOT “RFS specific error.” (Linux/i386 kernel specific.)
ENOTUNIQ “Name not unique on network.” (Linux/i386 kernel specific.)
EBADFD “File descriptor in bad state.” (Linux/i386 kernel specific.)
EREMCHG “Remote address changed.” (Linux/i386 kernel specific.)
ELIBACC “Cannot access a needed shared library.” (Linux/i386 kernel specific.)
ELIBBAD “Accessing a corrupted shared library.” (Linux/i386 kernel specific.)
ELIBSCN “.lib section in a.out corrupted.” (Linux/i386 kernel specific.)
ELIBMAX “Attempting to link in too many shared libraries.” (Linux/i386 kernel specific.)
ESTRPIPE “Streams pipe error.” (Linux/i386 kernel specific.)
EUCLEAN “Structure needs cleaning.” (Linux/i386 kernel specific.)
ENOTNAM “Not a XENIX named type file.” (Linux/i386 kernel specific.)
ENAVAIL “No XENIX semaphores available.” (Linux/i386 kernel specific.)
EISNAM “Is a named type file.” (Linux/i386 kernel specific.)
EREMOTEIO “Remote I/O error.” (Linux/i386 kernel specific.)
ENOMEDIUM “No medium found.” (Linux/i386 kernel specific, e.g., no CD in drive.)
EMEDIUMTYPE “Wrong medium type.” (Linux/i386 kernel specific, e.g., reading DVD in a CD-only drive.)
ENOKEY “Required key not available.” (Linux security keys or encryption context.)
EKEYEXPIRED “Key has expired.” (Key management or encryption issue.)
EKEYREVOKED “Key has been revoked.” (Key management or encryption issue.)
EKEYREJECTED “Key was rejected by service.” (Key management or encryption issue.)
ERFKILL “Operation not possible due to RF-kill.” A radio (Wi-Fi, Bluetooth) is disabled by the RF-kill switch.
EHWPOISON “Memory page has hardware error.” The system detected irrecoverable hardware memory corruption.
EBACKGROUND “Inappropriate operation for background process.” GNU/Hurd: the caller is not in the foreground process group for a terminal operation.
EDIED “Translator died.” GNU/Hurd: a file translator died before connecting to the file.
ED “?.” Humorously indicates “The experienced user will know what is wrong.”
EGREGIOUS “You really blew it this time.” A whimsical/humorous error code.
EIEIO “Computer bought the farm.” Another humorous error code: “Old MacDonald had a farm…”
EGRATUITOUS “Gratuitous error.” A purely whimsical error code with no real standard usage.

The exact set of error codes varies by platform, but all conforming C implementations will have at least a core subset of these.

3. Checking errno in practice

Below is an example of opening a file using fopen() and checking errno if the operation fails. We can use the C library functions perror() or strerror() to print human-readable messages describing the error.

// errno_example.c
#include 
#include 
#include 

int main(void) {
    FILE *fp = fopen("nonexistent.txt", "r");
    if (!fp) {
        // fp is NULL, so an error occurred
        fprintf(stderr, "Error opening file: %s\n", strerror(errno));
        // or use perror("Error opening file");
        return 1;
    }

    // Perform file operations...
    
    fclose(fp);
    return 0;
}

In this code, if fopen() fails, the program prints an error message indicating the reason, as dictated by errno. The function strerror(errno) translates the numeric errno into a descriptive string (e.g., "No such file or directory").

4. Error handling recommendations

  • Check return values: always check the return values of functions known to set errno (e.g., fopen, read, write, malloc in some cases, etc.).
  • Use perror or strerror: these functions clarify numeric error codes for easier debugging or user feedback.
  • Don’t overwrite errno prematurely: if you need to make multiple library calls after an error occurs, store the errno value somewhere before calling other functions that might reset it.
  • Thread awareness: in modern implementations, errno is thread-local, so you can safely use it in multi-threaded applications without conflict.

5. Conclusion

By consulting errno after a failed call, you can branch your code to handle specific conditions or provide clear diagnostics to users. Although errno has a global scope, modern implementations ensure it’s maintained per-thread, making it safe for concurrent applications. Together with perror() and strerror(), you can troubleshoot and handle a wide array of system and library errors in your C programs.

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access