How the Kernel Returns Errors and How errno Gets Set
The kernel returns -errno in the result register, and the C library turns values from -4095 to -1 into errno and a return of -1. See the raw path and the rules.

Every C programmer learns the same pattern: a call returns -1, you look at errno, and you find out what went wrong. It looks like a language feature, but it is not. The kernel does not know about errno at all. It returns a single number, and the C library invents the convention you use every day on top of that number. Seeing the layer below explains several odd behaviors, including why errno is only meaningful right after a failure and why some calls can never be told apart from success by return value alone. This post shows the raw path on x86-64 Linux with a 6.12 kernel and glibc 2.40.
What the kernel actually returns
A system call returns one value in the result register, rax on x86-64. For a call that fails, the kernel code returns a negative error number, written -EBADF, -ENOENT, -EINVAL and so on. The error constants are small positive integers defined in include/uapi/asm-generic/errno-base.h and errno.h: EPERM is 1, ENOENT is 2, EINTR is 4, EBADF is 9, ENOMEM is 12, EACCES is 13, EFAULT is 14 and EINVAL is 22. Kernel functions throughout the source return these negated, so return -ENOENT; appears in thousands of places.
There is no separate error flag on x86-64. The value in rax carries both the success result and the failure code, and one rule tells them apart.
The rule: the top 4095 values are errors
The kernel reserves the range from -4095 to -1 (as signed 64-bit integers) for errors. The macro that tests this in kernel source is IS_ERR_VALUE() in include/linux/err.h, built on the constant MAX_ERRNO, defined as 4095. Any return value in that range is an error. Every other value is a success.
That is why the kernel can return large positive numbers safely: the end of a successful mmap, a file offset from lseek, a byte count from read. Those are never in the top 4095 values because the top page of the address space is never handed out as a valid result. The rule is the reason you cannot confuse a legitimate pointer with an error.
Seeing the raw return value
You can bypass the C library and read the kernel's answer yourself. This program issues write with inline assembly on a file descriptor that is not open:
#include <stdio.h>
static long raw_write(int fd, const void *buf, unsigned long len)
{
long ret;
__asm__ volatile ("syscall"
: "=a"(ret)
: "a"(1L), "D"((long)fd), "S"(buf), "d"(len)
: "rcx", "r11", "memory");
return ret;
}
int main(void)
{
long r = raw_write(99, "x", 1);
printf("raw return: %ld\n", r);
return 0;
}raw return: -9The value -9 is -EBADF. No errno is involved, no -1 appears, and nothing in the program stores the error anywhere. The constraint letters bind the registers: a is rax, D is rdi, S is rsi, d is rdx. The rcx and r11 clobbers are there because the syscall instruction overwrites them with the return address and flags, and memory tells the compiler the call may read or write memory it cannot see.
What the C library adds
Now the same call through glibc:
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
ssize_t r = write(99, "x", 1);
printf("returned %zd, errno %d (%s)\n", r, errno, strerror(errno));
return 0;
}returned -1, errno 9 (Bad file descriptor)Between the two programs, glibc's write wrapper ran code with this logic after the syscall instruction: if the result in rax is an unsigned value above -4096 (the same top-4095 range), store the negation of it in errno and return -1; otherwise return the value unchanged. Internally that is a branch on rax > -4096 in sysdeps/unix/sysv/linux/x86_64/sysdep.h. The convention "-1 and errno" is a promise glibc makes for the whole standard C interface, not something the hardware or the kernel provides.
errno is a thread-local variable
errno looks like a global variable, but glibc defines it as a macro that expands to (*__errno_location()). That function returns the address of a per-thread integer. Each thread has its own copy, so a failing call in one thread cannot overwrite the error another thread is about to read. The thread-local storage is part of the thread control block, reached through the fs segment register on x86-64.
This design has two consequences worth writing down.
**Read
errnoimmediately.** A successful call is allowed to changeerrno, because the C standard says only that a library function may set it to a nonzero value even on success. The meaningful time to read it is right after a call that reported failure.Save it before doing anything else. If you call
printfbetween the failure and the check,printfmay itself callwriteand seterrnoagain. The safe pattern isint saved = errno;first.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
int fd = open("/no/such/file", O_RDONLY);
if (fd < 0) {
int saved = errno;
fprintf(stderr, "open failed\n");
fprintf(stderr, "reason: %s\n", strerror(saved));
return 1;
}
return 0;
}open failed
reason: No such file or directoryUsing saved makes the second message correct even if the first fprintf had changed errno.
Calls where -1 is not the error signal
The "-1 plus errno" pattern covers most system calls, but not all. The glibc manual and the Linux manual pages list the exceptions, and they matter because checking the wrong thing hides failures.
| Call | How failure is signalled |
|---|---|
read, write, open | return -1, set errno |
mmap | returns MAP_FAILED, which is (void *)-1, sets errno |
getpriority | -1 can be a valid priority, so set errno = 0 first and test it afterward |
pthread_create and most POSIX thread functions | return the error number directly, do not touch errno |
strtol | returns LONG_MAX or LONG_MIN on overflow and sets errno to ERANGE |
The POSIX thread functions are the common trap. They return 0 on success and a positive error number such as EAGAIN on failure, and errno is not set. Code that tests if (pthread_create(...) == -1) never fires. The getpriority case shows why the rule "errno is only meaningful after failure" is incomplete: when -1 is a legitimate result, you clear errno before the call and inspect it afterward.
Turning an error number into text
The kernel never sends text; the strings come from the C library. strerror(errno) returns a description such as "No such file or directory", and perror("prefix") prints it with a prefix to standard error. Both depend on the locale. For logs that must be stable and machine-readable, glibc 2.32 added strerrorname_np(), which returns the symbolic name such as "ENOENT", and strerrordesc_np() for the untranslated description. These are the _np (non-portable) functions, so they are glibc-specific.
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
printf("%s: %s\n", strerrorname_np(ENOENT), strerrordesc_np(ENOENT));
printf("%s: %s\n", strerrorname_np(EACCES), strerrordesc_np(EACCES));
return 0;
}ENOENT: No such file or directory
EACCES: Permission deniedWhen the convention differs
The top-4095 rule is the Linux convention for x86-64, ARM64 and RISC-V. A few older ABIs signal errors differently: on some architectures, such as MIPS and Alpha, the kernel returns a positive error value and sets a separate flag register, and the C library reads that flag. Application code never sees the difference, because the libc wrapper hides it. Only code that issues raw system calls, like the assembly above, must follow the target ABI, and it should consult the syscall(2) manual page for it.
A small helper for readable errors
Repeating the same check and message for every call clutters code. glibc offers error() in <error.h> and the BSD-style err() family in <err.h>, which print the program name, a message and the text for errno, and optionally exit. A short wrapper keeps the pattern uniform and saves errno before anything else can change it:
#include <err.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd = open("/no/such/file", O_RDONLY);
if (fd < 0)
err(1, "open /no/such/file"); /* adds ": No such file or directory" */
close(fd);
return 0;
}die: open /no/such/file: No such file or directoryerr() reads errno itself, formats the message, and exits with the given status, while warn() does the same without exiting. The program name, here die, comes from argv[0]. These functions are not part of POSIX, though they exist on glibc, musl and the BSDs. For portable code, write a small die() that captures errno into a local variable first, calls strerror, prints to standard error and exits. Whichever helper you use, the habit that matters is the same: the text of the failure reaches the person who needs it, with the name of the operation and the object it concerned.


