The invisible variable that tells your computer why it failed

The invisible variable that tells your computer why it failed
Image: Intellect (generated)

In short: When a program crashes or fails to open a file, how does the code know what went wrong? It relies on a subtle mechanism in the C programming language called errno. This global-like integer captures the 'why' behind every system error, acting as a silent messenger between software and hardware.

In the C programming language, <errno.h> is the header file responsible for reporting and retrieving error conditions. It defines macros that allow developers to access a symbol called errno—short for 'error number.' When a library function encounters an issue, it typically returns a special value (like NULL or -1) to signal a failure. However, these return values are often generic; the specific reason for the failure is stored in the errno variable.

The mechanism of errno has evolved significantly with modern computing. Originally, it was a static memory location, but this caused issues in multi-threaded environments where different threads might overwrite each other's errors. Today, macros ensure that errno is thread-local, meaning every thread maintains its own unique error number. At program startup, the value is initialized to zero, and library functions only store values greater than zero when an error occurs.

While the C standard requires only three basic error constants, POSIX-compliant systems like Linux or Solaris include many more, such as EACCES for permission issues. A critical nuance for developers is that while macro names are defined by POSIX standards, their numeric values are not. This means programmers should never rely on specific numbers; instead, they must test against the standard macro names to ensure portability across different Unix versions.

To make these errors human-readable, functions like strerror translate the integer into a descriptive string, while perror prints it directly to the standard error stream. Because some of these translation methods are not thread-safe, developers may use alternatives like strerror_r, though these can vary between POSIX and GNU definitions.

Opens the Intellect+ feed with this card first. Swipe up for the next one.

Sources

  • Summary by Intellect · source: Errno.h

To cite this card, link to https://intellectplus.co.uk/app/science-errno-h.

How we source, check and correct cards: Editorial standards.

General information, not professional advice. Spotted an error? Flag the card or see corrections and complaints.

Intellect Plus is a visual educational discovery platform for exploring fascinating facts and ideas. Brain Food, Not Brain Rot. What is Intellect Plus?

Related

Finding something worth knowing…