Skip to content
systemcoding.dev
Systems Programming

Write Errors to stderr with perror and err

Report failures from a C tool the Unix way: perror, strerror and the err and warn family, with errno saved correctly and messages sent to stderr.

6 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Rust and FreeBSD logos.

When a system call fails, the kernel tells your program why through a number, and a good command-line tool turns that number into a sentence a person can act on, on the right stream, with the right exit status. C gives you several ways to do it: perror, strerror with fprintf, and the BSD err and warn family. This post shows what each one prints on Linux with glibc 2.40, when to use which, and the traps around errno that make messages lie. It belongs to the guide to building command-line tools in C.

Why errors go to stderr

A program has two output streams so that results and complaints do not mix. Standard output, descriptor 1, carries the data a pipeline passes along. Standard error, descriptor 2, carries messages for a human. If a tool prints cannot open file on standard output, the next program in the pipeline reads that sentence as data. Descriptor 2 is also unbuffered by default in C, so a message appears the moment it is written, even if the program then crashes with output still waiting in the standard output buffer.

errno in one paragraph

Most system calls and many library functions report failure by returning a special value, such as -1 or NULL, and setting the thread-local integer errno to a code that says why. The codes are macros from <errno.h>: ENOENT for a missing file, EACCES for a permission problem, EEXIST, EINVAL, ENOMEM and so on. Two rules govern it. errno is meaningful only right after a call that failed, because a successful call may change it and does not reset it to zero. And you must read it before calling anything else that might change it, including printf.

perror

perror is the oldest tool. It is declared in <stdio.h>, takes a prefix string and prints the prefix, a colon, a space, the text for the current errno and a newline, all to standard error.

perror1.cc
#include <stdio.h>

int main(void)
{
    FILE *f = fopen("/nonexistent/data.txt", "r");
    if (f == NULL) {
        perror("data.txt");
        return 1;
    }
    fclose(f);
    return 0;
}

The program prints on standard error:

Text
data.txt: No such file or directory

If you pass NULL or an empty string, only the message appears. perror is short and correct, and it is the right choice for a one-off check. Its limits are that it does not know the program's name, so the output does not say who complained, and that it cannot format a message with values, so "cannot open %s at line %d" takes a separate snprintf first.

strerror and fprintf

When you need a formatted message, convert the code to text yourself with strerror, declared in <string.h>, and print with fprintf:

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

int main(int argc, char *argv[])
{
    const char *path = argc > 1 ? argv[1] : "config.ini";
    FILE *f = fopen(path, "r");

    if (f == NULL) {
        fprintf(stderr, "%s: cannot read %s: %s\n", argv[0], path, strerror(errno));
        return 1;
    }
    fclose(f);
    return 0;
}

Running ./strerror1 /etc/shadow as a normal user prints:

Text
./strerror1: cannot read /etc/shadow: Permission denied

The format starts with the program name, because logs interleave output from many processes, and it names the object the error is about. That shape, program, object, reason, is the one users recognise from ls, cp and grep.

strerror has a catch in threaded programs. POSIX allows it to return a pointer to a buffer that a later call overwrites, so portable threaded code uses strerror_r, which fills a buffer you provide. Take care with its signature: glibc's non-POSIX variant, the default under _GNU_SOURCE, returns a char *, while the POSIX variant returns an int. A single-threaded tool can use strerror without concern, and warn and err below avoid the question.

The err and warn family

BSD systems defined a family in <err.h> that does the common job in one call, and glibc and musl both provide it. It prints the program name, a colon, the formatted message, and if the function is the errno kind, a colon and the system message.

FunctionPrints errno textExits
warn(fmt, ...)YesNo
warnx(fmt, ...)NoNo
err(code, fmt, ...)YesYes, with code
errx(code, fmt, ...)NoYes, with code

The program name comes from the C library, derived from argv[0] with the directory removed, so you never format it by hand. The same example with err:

err1.cc
#include <err.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    const char *path = argc > 1 ? argv[1] : "config.ini";
    FILE *f = fopen(path, "r");

    if (f == NULL)
        err(EXIT_FAILURE, "cannot read %s", path);
    fclose(f);
    return 0;
}

Invoked as ./err1 missing.ini, it prints and exits with status 1:

Text
err1: cannot read missing.ini: No such file or directory

The message is shorter than in the earlier example, because the library supplied the program name without the leading ./. For a message that has no system cause, such as a bad option value, use errx or warnx: errx(2, "invalid count: %s", optarg) prints err1: invalid count: abc and exits 2.

Keep going or stop

The pairs warn and err encode a decision every tool makes. A failure that affects one input among many is reported with warn, the tool continues, and the final exit status is nonzero. A failure that makes continuing pointless, such as an inability to write the output or to allocate memory, is reported with err, which exits at once. The loop over files in a tool like a cat clone uses both: warn for an unreadable file and err for a write error.

err calls exit, so buffered output is flushed and atexit handlers run. In a forked child that must not do either, call warn and then _exit.

Saving errno

The most common bug in error reporting is that errno changes between the failure and the message. Any library call, even fprintf, can set it. Here is a message that lies:

c
FILE *f = fopen(path, "r");
if (f == NULL) {
    printf("opening %s failed\n", path);
    perror(NULL);
}

The first use of a buffered stream such as standard output makes the library probe whether it is a terminal, and that probe can set errno to ENOTTY. The output then reads Inappropriate ioctl for device after a missing-file error, which sends someone chasing the wrong cause. The safe pattern is to read the value into a local variable immediately:

c
FILE *f = fopen(path, "r");
if (f == NULL) {
    int saved = errno;
    printf("opening %s failed\n", path);
    errno = saved;
    perror(NULL);
}

Cleanup code has the same problem. If a function fails, then calls close and free before returning, those calls can overwrite errno, so save it before the cleanup and restore it afterwards, as the cat clone does.

What not to do

  • Do not print errors on stdout. A pipeline will treat them as data.

  • **Do not call perror after a successful call.** errno may hold a stale value from an earlier failure, so the message names an error that did not happen. Check the return value first.

  • **Do not compare errno to zero to detect failure.** Only the return value says whether a call failed. A few functions, such as strtol, require you to set errno = 0 first and check it afterwards, which the documentation says explicitly.

  • Do not write messages as complete sentences with punctuation. They are parsed by eye and by scripts, and the convention is lower case with no trailing full stop.

  • Do not hide the reason. error: failed helps nobody. Keep the system text.

Messages for scripts and logs

If your tool's messages are consumed by scripts, keep them stable and put the program name first. If they go to a log through syslog, the format changes: syslog(LOG_ERR, "cannot read %s: %m", path) uses the glibc %m format, which inserts the text for errno and works without calling strerror. For a daemon with no terminal, that is the right route, and standard error may be closed or redirected to a file.

For a tool with a --verbose option, a short message by default and extra detail under the flag is a good split. The errno text stays in both.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.