Skip to content
systemcoding.dev
Systems Programming

The Complete Guide to Error Handling in Systems Code

How systems code reports, checks, cleans up after and tests failures: errno, short writes, goto cleanup, fault injection and error design in C, Rust and Go.

25 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the C, Rust and Linux logos.

Systems code fails constantly and in small ways. A file is missing, a disk is full, a peer hangs up, a signal arrives in the middle of a read, an allocation is refused. Application programmers can often let a framework turn those events into a generic error page. Systems programmers cannot, because the program is the layer other programs stand on, and a mishandled write in a library becomes data loss in every program that links it. This guide covers the whole subject in one place: how the operating system reports failure, how to read the contract of a call, how to check results without cluttering the code, what to do with errno, how to clean up on every exit path, how to design error handling for a library, how Rust, Go, C++ and Zig approach the same problems, and how to test the paths that almost never run. It is written for C11 and POSIX.1-2024 on Linux 6.x with glibc 2.41, and the other languages are shown at the versions named in each section. The primary sources are the POSIX specification, the Linux man-pages project and the GNU C Library manual. Each section links forward to a focused post in this cluster, so you can use the guide as a map and dig into the part you need.

Start with two kinds of failure

Before any technique, separate two things that look alike in code. A runtime failure is something the environment did to a correct program: the file does not exist, the network is down, the disk is full. The program is right, the world is not, and the correct response is to detect the failure, clean up, report it clearly and, where possible, recover. A programming error is something the program did to itself: a null pointer passed where the contract forbids it, an index out of range, a function called in the wrong order. The correct response to those is usually to fail loudly and early, with assert or an abort, because carrying on with a corrupted state makes the eventual failure harder to trace.

The mistake that causes most trouble is treating one kind as the other. Code that tries to "recover" from a null pointer by returning -1 hides a bug that should have crashed a test. Code that aborts when open fails turns a missing file into a crashed server. Decide, for each failure, which kind it is, and let that choose the mechanism. The rest of this guide is almost entirely about runtime failures, because those are the ones that need design.

KindExampleRight response
Runtime failureopen returns ENOENTReport, clean up, recover or propagate
Resource exhaustionmalloc returns NULLFail the operation, free what you hold, propagate
Programming errorNULL passed to a function that forbids itassert, fix the caller
Corrupt internal stateA checksum of your own data failsAbort with a message, since continuing spreads damage

How the operating system reports failure

Every error you handle in C began as the kernel's answer to a system call. On Linux, a call returns its result in one register, and a failure is a negated error number between -4095 and -1. The C library wraps each call, notices a value in that range, stores the positive number in the thread's errno and returns -1. The post on raw syscall return values explains the boundary in detail, and the practical result is the convention you code against: a function returns a special value to say "failed", and errno says why.

The special value is not the same for every function, and that is the first thing to learn. Most system calls return -1. Functions that return pointers return NULL, with the notable exception of mmap, which returns the constant MAP_FAILED. The pthread family returns the error number directly and leaves errno alone. Functions such as strtol have no failure value at all and rely on you to clear errno first. The table below is the one to keep nearby, and the post on checking return values covers each case.

Function familyHow failure is signalledWhere the reason is
open, read, write, close, socketreturn -1errno
malloc, calloc, fopenreturn NULLerrno
mmapreturns MAP_FAILEDerrno
pthread_mutex_lock, pthread_createreturn a positive error numberthe return value
strtol, strtodno unique valueerrno, only if cleared before the call
printf familyreturn a negative counterrno
fgets, freadNULL or a short countferror and feof, plus errno

Notice what the table means in practice. There is no single if (rc < 0) test that works across the standard library. Every call needs its documented test, which is why the first habit of a careful systems programmer is to read the RETURN VALUE section of the man page before writing the line.

Read the contract: the man page is the specification

Every system call and library function documents its own failure behavior, and the documentation is more precise than most programmers assume. Open the page with man 2 open and look at three sections. RETURN VALUE says what signals failure. ERRORS lists every errno value the call may set and the condition behind each one. NOTES and VERSIONS record the traps, such as "since Linux 3.11" or "the glibc wrapper differs from the raw call".

Read the ERRORS list for conditions, not just names. The entry for EINVAL in read says that the descriptor was opened with O_DIRECT and the buffer is misaligned, which no amount of staring at the error name would tell you. The post on matching the man page to strace output walks through that exact diagnosis. A useful habit when writing a failure branch is to ask which of the listed errors can actually occur here and which of them deserve different handling. For open, ENOENT may mean "create it", EACCES means "report the permission problem", EMFILE means "you have a descriptor leak", and EINTR means "try again". A single generic branch that prints "open failed" throws away the information the call gave you.

Check every call, in the way that call needs

The cheapest rule in systems programming is also the most often broken: check the result of every call that can fail. The cost is a line or two. The cost of not checking is a program that reports success after a failed write.

For the common -1 pattern the check is short:

c
int fd = open(path, O_RDONLY);
if (fd == -1) {
    perror(path);
    return -1;
}

Short reads and writes need a loop, because a successful write may write fewer bytes than you asked, especially on pipes, sockets and terminals. The loop advances a pointer by the returned count and retries on EINTR. The post on return values contains the write_all and read_all helpers, and the code below is the essence:

write_all.cc
#include <errno.h>
#include <stddef.h>
#include <unistd.h>

int write_all(int fd, const void *buf, size_t len)
{
    const char *p = buf;
    while (len > 0) {
        ssize_t n = write(fd, p, len);
        if (n == -1) {
            if (errno == EINTR)
                continue;
            return -1;
        }
        p += n;
        len -= (size_t)n;
    }
    return 0;
}

Two checks are routinely forgotten. The first is close, which can report a deferred write error on network filesystems, so a program that writes a file and ignores close can report success on a truncated file. The second is fclose or fflush on a buffered stream, where the write error appears at flush time, long after the fprintf that supplied the data. For a file whose contents matter, check both, and call fsync before close when the data must survive a crash.

A compiler can help. With glibc, -O2 -D_FORTIFY_SOURCE=2 -Wall makes read and write warn when the result is ignored, and a cast to void becomes a visible, deliberate decision that deserves a comment explaining why the failure is acceptable.

errno: the rules that prevent most bugs

errno is a per-thread integer from <errno.h>, and the post on what errno is covers its definition. The rules that matter in practice are few.

Read it only after a failure. A successful call may leave errno at any value, and no standard function sets it to zero. The test is always the return value first, and errno second.

Copy it before you do anything else. Any later call, including close, free and fprintf, may overwrite it. The pattern is a local variable assigned right after the failing call, and an assignment back before returning if the caller is going to read it. The post on preserving errno across cleanup and logging builds this into a guard macro and a rule for logging helpers.

Clear it only where the contract demands. For strtol, strtod and a few others, the documented method is errno = 0 before the call and a test afterward, because the return value alone cannot distinguish an error from a legitimate result.

It is thread-local, and signal handlers share it. The post on why errno is thread-local explains how glibc expands the name to *__errno_location(). That protects you from other threads, and does nothing to protect you from a signal handler that runs on your own thread between a failing call and the line that reads the value. A handler that calls anything that can fail must save and restore errno.

Never declare it yourself. extern int errno; is wrong wherever errno is a macro, which is everywhere that supports threads. Include the header.

The raw convention under all this, a negative number in a register, matters when you step below libc. If you call the kernel through syscall(2) you still get the libc convention, and if you use inline assembly or a libc-free runtime you decode the range -4095 to -1 yourself. The post on raw syscall values includes both a syscall() call and a hand-rolled assembly call, and shows that the same failure appears as -1 with errno set in one and as -2 in the other.

Turn numbers into messages for people

A number is for the program, and a sentence is for the person. The standard library offers perror, which prints a prefix, a colon and the message for the current errno to standard error, and strerror, which returns the message as a string. The post on strerror and perror gives the rules: use perror for a quick report from a command-line tool, use strerror when you build your own message, and never compare against message text, because it varies between libraries and locales.

Thread safety makes the story more complicated. strerror may return a pointer into a shared buffer, so threaded programs use strerror_r, which has two incompatible signatures in glibc, the GNU one returning a pointer and the XSI one returning an integer. The post on using strerror_r correctly shows a wrapper that works under both and mentions strerror_l, which sidesteps the issue. A message should name the operation and the object, not only the reason:

c
fprintf(stderr, "%s: cannot open %s: %s\n", prog, path, strerror(errno));
Text
backup: cannot open /var/data/config.db: Permission denied

The program name tells the reader which tool complained, the path says what it tried to touch, and the reason says why it failed. Each part saves a round of questions in a bug report.

Know the errors that appear again and again

A short list of errno values accounts for most of what you will meet, and knowing what each one implies tells you how to react. The post on common errno values keeps the full table with a "when not to retry" note for each. The essentials are these.

ENOENT means the path does not exist, and it is not worth retrying. EACCES and EPERM mean permission was refused, and again no retry will help, though they differ: EACCES refuses access to a file, and EPERM refuses the operation itself. EEXIST after an exclusive create is often the success signal you wanted, meaning another process won a race. EINTR means a signal interrupted a blocking call, and retrying is usually right, except for close on Linux. EAGAIN on a non-blocking descriptor means "not now", and the response is to wait for readiness, not to loop. EINVAL means an argument is wrong, and a retry repeats the failure. EMFILE means you have run out of descriptors, which usually points to a leak, and ENOSPC means a full disk, which will not clear by waiting. EPIPE arrives with SIGPIPE, which kills the process unless you ignore it.

The reaction matters more than the name. A retry on a permanent error spins forever. A failure on a transient one drops work that would have succeeded a millisecond later. Group errors into three buckets when you design a handler: permanent (report and stop), transient (retry or wait), and caller-fault (a bug in the arguments, fix the code).

Non-blocking and partial progress

Event-driven programs use non-blocking descriptors, and there a call may succeed partly. A write of a megabyte takes what the kernel will hold and returns that count, and a read returns what has arrived. The state of the transfer, how many bytes are done, has to live somewhere between calls, and the cleanest place is next to the data. The post on non-blocking helpers builds a small out_buf and in_buf pair with a flush_out and fill_in function that return IO_DONE, IO_WOULDBLOCK, IO_EOF or IO_ERROR, and a poll loop that resumes at the saved offset.

The lesson generalizes beyond sockets. Any operation that can stop in the middle needs its progress recorded, and the error handling needs a result that says "not finished, ask again" in addition to "done" and "failed". Collapsing the three into success and failure is how programs lose the tail of a message.

Clean up on every exit path

A function that acquires resources in sequence has an exit path for each point where a later step can fail, and every path must release exactly what was acquired so far. Written naively, the function either nests deeper with each resource or repeats cleanup code that goes out of sync. There are three good answers in C.

The first is the **goto cleanup chain**: one list of labels at the bottom, in the reverse order of acquisition, with each failure jumping to the label that releases what is held. The post on goto cleanup shows the pattern with a lock, a buffer and a descriptor, records the error code in a local before cleanup, and sets errno once at the end. It is plain C that every compiler accepts, and the Linux kernel's coding style documents it.

The second is the **cleanup attribute** from GCC and Clang, which runs a function when a variable leaves scope. The post on __attribute__((cleanup)) builds autofree, autoclose and autounlock macros and a steal macro for handing ownership out, and lists where it does not run: exit, longjmp and a forked child. It removes the labels at the price of portability to compilers that lack the attribute.

The third is restructuring into smaller functions, where each function owns one resource and returns early, and the caller composes them. It is the right answer when the acquisitions are independent.

c
int load(const char *path, struct config *out)
{
    int err = 0;
    int fd = open(path, O_RDONLY);
    if (fd == -1) { err = errno; goto out; }

    char *buf = malloc(4096);
    if (!buf) { err = ENOMEM; goto out_close; }

    if (read(fd, buf, 4096) == -1) { err = errno; goto out_free; }

    err = parse_config(buf, out);

out_free:
    free(buf);
out_close:
    close(fd);
out:
    errno = err;
    return err ? -1 : 0;
}

Whichever you choose, apply it consistently across a code base, because a reviewer needs to know where to look for the release of a resource.

Cleaning up when the exit is not normal

Cleanup code assumes control returns through the function. Several exits bypass it. exit runs atexit handlers and flushes stdio, and _exit does neither. A fatal signal runs nothing, so buffered output is lost and temporary files stay on disk. longjmp abandons frames without releasing what they held, and the post on setjmp and longjmp shows why: the saved registers say nothing about the heap.

Design for it. Write temporary files in the destination directory and finish with rename, so a crash leaves either the old file or the new one, never a half-written file. Register a signal handler for SIGTERM and SIGINT that sets a flag, and let the main loop clean up and exit normally. Keep the work in a handler to the async-signal-safe list, which excludes printf and malloc. For long-running servers, flush logs after each line or write them with write directly, so a crash does not take the last seconds of evidence with it, and the post on controlling stdio buffering with setvbuf explains the mechanics.

Atomic updates for files

Error handling at the file level has one idiom that every systems programmer should know. To replace the contents of a file safely, write the new contents to a temporary file in the same directory, call fsync on it, and rename it over the old name. The rename is atomic on POSIX filesystems, so a reader sees either complete version, and a failure at any step leaves the original untouched.

c
int save_atomic(const char *dir, const char *name, const char *data, size_t len)
{
    char tmp[4096], final[4096];
    snprintf(tmp, sizeof tmp, "%s/.%s.tmp", dir, name);
    snprintf(final, sizeof final, "%s/%s", dir, name);

    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        return -1;

    if (write_all(fd, data, len) == -1 || fsync(fd) == -1) {
        int saved = errno;
        close(fd);
        unlink(tmp);
        errno = saved;
        return -1;
    }
    if (close(fd) == -1) {
        int saved = errno;
        unlink(tmp);
        errno = saved;
        return -1;
    }
    if (rename(tmp, final) == -1) {
        int saved = errno;
        unlink(tmp);
        errno = saved;
        return -1;
    }
    return 0;
}

Every failure path removes the temporary file and preserves the original error, which is the whole discipline of this guide in one function. The durable version also syncs the directory after the rename, so the new name itself survives a power loss.

Design the error interface of a library

When you write a library, your error handling becomes your callers' contract, and it becomes part of the ABI. The post on return codes versus out-parameters compares five designs: a sentinel with errno, direct error codes, error objects through an out-parameter, result structs and callbacks. The summary is that errno suits thin wrappers over the OS, direct codes suit thread-safe libraries with their own namespace, error objects suit libraries whose failures need context, and result structs suit small hot functions.

Several rules hold for every design. Publish the list of codes each function may return, and treat that list as stable. Reserve the right to add codes, and tell callers to treat unknown ones as general failure. Never use a shared global for the last error unless it is thread-local. Decide the out-of-memory path first, since reporting an allocation failure must not need an allocation. And never print from a library: return the error and let the program choose how to show it, because it may be a daemon with its own logger or a GUI with no standard error.

Errors in other languages

The same problems appear in every systems language, solved with different tools. The common thread is that a good design puts the error in a value that cannot be overwritten, and makes ignoring it visible.

Rust returns Result<T, io::Error>. The error value carries the OS code, readable through raw_os_error, and a portable ErrorKind for decisions. The ? operator propagates, and the standard library retries Interrupted itself. The post on mapping OS errors in Rust shows how to match NotFound, compare raw_os_error() against libc::ENOSPC and wrap errors with a source chain.

Go returns an error and wraps OS failures in *fs.PathError around a syscall.Errno. Comparison goes through errors.Is and errors.As, not ==, and wrapping with %w keeps the chain. The post on Go syscall errors covers fs.ErrNotExist and the traps of %v.

C++ offers std::error_code with std::system_category() and portable comparison against std::errc, and the standard filesystem library gives every function a throwing and a non-throwing form. The post on std::error_code shows both forms and how to write your own function in that style.

Zig makes errors a language feature: an error union E!T, with try, catch and errdefer, and the standard library maps errno to named errors at the boundary. The post on Zig error sets shows the mapping and the exhaustive switch.

Windows keeps a per-thread last-error value read with GetLastError and formatted with FormatMessageW. Registry functions return codes directly, and HRESULT is a third system. The post on Win32 errors builds a safe formatting helper.

LanguageWhere the failure livesHow you propagateWhat you must remember
Creturn value plus errnomanual if and returnCopy errno before cleanup
RustResult<T, E>? operatorAdd context with a wrapper type
Goerror valueif err != nilWrap with %w, compare with errors.Is
C++exception or error_codethrow or return codePick one style per API
Zigerror uniontryerrdefer for partial work
Win32last-error valuemanualRead it immediately, and registry calls differ

Fatal errors, assertions and exit codes

Some failures should end the program. A tool that cannot open its input has nothing to do, and a helper that prints the reason and exits is the right shape.

c
void die(const char *fmt, ...)
{
    int saved = errno;
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    if (saved != 0)
        fprintf(stderr, ": %s", strerror(saved));
    fputc('\n', stderr);
    exit(1);
}

Use exit and not abort for expected failures, because exit flushes buffers and runs atexit handlers, and abort raises SIGABRT and typically produces a core dump. Reserve abort and assert for invariant violations, where a core dump is exactly what you want. Compile without -DNDEBUG in tests, since that flag removes every assert.

Exit codes are an interface too. Zero means success, and non-zero means failure, with the convention that 1 is a general error, 2 often a usage error, and values from 126 to 128 are used by the shell for "cannot execute", "not found" and "killed by signal". Documenting distinct codes for distinct failure classes lets scripts react, as with grep, which returns 1 for "no match" and 2 for a real error.

Log so the next person can diagnose

A message at the point of failure should answer who, what, which object and why. Include the operation name, the path or address, the numeric errno and its text, and, for network errors, the peer. Include a request or connection identifier when there is one. Write to standard error for tools, and to the structured log for services.

Do not log the same failure at every level of the call stack. The usual rule is to handle an error where it can be acted on and log it there, and to return it everywhere else. Logging at each frame produces five lines for one event and makes the real cause hard to find. When you wrap an error to add context, as the Rust and Go examples do, the context goes in the wrapper and the final handler logs the whole chain once.

Take care with sensitive information. An error message that echoes a password from a configuration file, or a full filesystem path to a remote client, leaks data. Keep detail for the local log, and show the remote user a short, stable message.

Retries, timeouts and idempotency

Transient errors invite retries, and a careless retry loop is its own bug. Three rules keep it safe. Bound it: a fixed number of attempts or a total time limit, so a dead peer cannot hold a thread forever. Back off: wait longer between attempts, with random jitter, so many clients do not retry in lockstep. Know the operation is safe to repeat: reading is, writing a fixed offset is, appending a record is not, and sending a payment request is not unless it carries an idempotency key.

EINTR is the one case where retrying immediately is always right for read, write, open and accept, and the retry costs nothing because no work was done. EAGAIN on a non-blocking descriptor is different: retry only when poll says the descriptor is ready. A timeout on connect deserves a limited retry, and ECONNREFUSED usually does not, since the host answered and said no.

Testing the paths that never run

Error handling code runs least, so it breaks most. Test it on purpose. The cheapest techniques need no changes to the program.

Pick a path that fails. Open a file that does not exist. Open /dev/full, which accepts opens and fails every write with ENOSPC. Read from a descriptor you have closed to get EBADF.

**Inject failures with strace.** The post on strace -e inject shows how to make a chosen call fail with a chosen error: strace -P note.txt -e trace=write -e inject=write:error=ENOSPC ./app forces the write to fail without touching the program, and a loop over openat, write and close walks every branch.

**Interpose with LD_PRELOAD.** The post on wrapping libc functions builds a shared library that fails the Nth malloc or counts calls, using dlsym(RTLD_NEXT, ...) to reach the real function.

Use a fault-injecting allocator. In Zig, std.testing.FailingAllocator fails the Nth allocation. In C, a wrapper around malloc with a countdown does the same.

Run under sanitizers. AddressSanitizer and LeakSanitizer find the leaks that error paths produce, and a test that forces each failure in turn then checks the descriptor count with /proc/self/fd, finds the descriptor leaks sanitizers miss.

Assert on the result, not on the message: the exit status, the errno value, the error kind. Messages change, and a test that matches them breaks with every wording edit.

Security and error handling

Errors are a security surface. A few patterns recur.

Check-then-use races. Testing a file with access or stat and then opening it leaves a window in which the file can be replaced, a flaw called time-of-check to time-of-use. Open the file and handle the failure, using O_NOFOLLOW and openat where symbolic links matter.

Unchecked results that become vulnerabilities. An ignored setuid failure leaves a program running as root when it meant to drop privilege, and the check of its result is not optional. The same goes for chroot and setgid.

Information leaks. Different error messages for "no such user" and "wrong password" tell an attacker which names exist. Return the same message and log the difference locally.

Resource exhaustion. A server that does not handle EMFILE can be pushed into a loop of failed accept calls. Handle it by closing an idle connection or pausing accepts, and not by spinning.

Format strings. Passing an error message you built from external data as the format to printf allows %n and other conversions to act on memory. Always write printf("%s", msg).

A catalogue of common mistakes

These are the mistakes that show up again and again in review, each with its fix.

  • **Ignoring the return value of write, read, close or fclose.** Check them, and loop on short counts.

  • **Reading errno after a success.** Test the return value first.

  • **Calling cleanup before saving errno.** Save first, then clean, then restore.

  • **Testing mmap against NULL.** It returns MAP_FAILED.

  • **Treating pthread_* return values as -1 plus errno.** They return the number itself.

  • **Retrying close after EINTR on Linux.** The descriptor is already closed.

  • **Spinning on EAGAIN.** Wait with poll or epoll.

  • **Using strerror from several threads.** Use strerror_r or strerror_l.

  • Comparing against message text. Use the error number or kind.

  • Passing user input as a format string. Use "%s".

  • Logging at every level. Log once, where the error is handled.

  • Exiting with status 0 after a reported failure. Return a non-zero code.

  • Leaving a half-written file after a crash. Write to a temporary file and rename.

Putting it together in one small tool

Every idea above shows up in a program as small as a file copy. The tool below copies one file to another, and it is written to follow the guide: it checks each call, loops on short counts, preserves the original error through cleanup, writes to a temporary file and renames it, and exits with a distinct status for usage errors and I/O failures. Reading it as a whole is the best way to see how the pieces fit.

cpfile.cc
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static int write_all(int fd, const char *p, size_t len)
{
    while (len > 0) {
        ssize_t n = write(fd, p, len);
        if (n == -1) {
            if (errno == EINTR)
                continue;
            return -1;
        }
        p += n;
        len -= (size_t)n;
    }
    return 0;
}

static int copy(const char *src, const char *dst)
{
    int err = 0;
    char tmp[4096];
    snprintf(tmp, sizeof tmp, "%s.tmp", dst);

    int in = open(src, O_RDONLY);
    if (in == -1) {
        err = errno;
        fprintf(stderr, "cpfile: cannot open %s: %s\n", src, strerror(err));
        goto out;
    }

    int out = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (out == -1) {
        err = errno;
        fprintf(stderr, "cpfile: cannot create %s: %s\n", tmp, strerror(err));
        goto out_close_in;
    }

    char buf[65536];
    for (;;) {
        ssize_t n = read(in, buf, sizeof buf);
        if (n == -1) {
            if (errno == EINTR)
                continue;
            err = errno;
            fprintf(stderr, "cpfile: read %s: %s\n", src, strerror(err));
            goto out_unlink;
        }
        if (n == 0)
            break;
        if (write_all(out, buf, (size_t)n) == -1) {
            err = errno;
            fprintf(stderr, "cpfile: write %s: %s\n", tmp, strerror(err));
            goto out_unlink;
        }
    }

    if (fsync(out) == -1) {
        err = errno;
        fprintf(stderr, "cpfile: fsync %s: %s\n", tmp, strerror(err));
        goto out_unlink;
    }
    if (close(out) == -1) {
        err = errno;
        out = -1;
        fprintf(stderr, "cpfile: close %s: %s\n", tmp, strerror(err));
        goto out_unlink;
    }
    out = -1;
    if (rename(tmp, dst) == -1) {
        err = errno;
        fprintf(stderr, "cpfile: rename to %s: %s\n", dst, strerror(err));
        goto out_unlink;
    }
    close(in);
    return 0;

out_unlink:
    if (out != -1)
        close(out);
    unlink(tmp);
out_close_in:
    close(in);
out:
    errno = err;
    return -1;
}

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "usage: cpfile SOURCE DEST\n");
        return 2;
    }
    return copy(argv[1], argv[2]) == 0 ? 0 : 1;
}

Running it on a missing source shows the report that names the operation, the object and the reason, and the exit status separates a usage error from an I/O failure.

Text
$ ./cpfile /no/such/file out.txt
cpfile: cannot open /no/such/file: No such file or directory
$ echo $?
1
$ ./cpfile
usage: cpfile SOURCE DEST
$ echo $?
2

Look at what the structure buys. Each failure records its reason in err at the moment it happens, so no cleanup call can replace it. The labels release the resources held at each point in reverse order, so there is exactly one copy of each close and unlink. The temporary file means a failure at any step leaves the destination as it was, and the final rename is the single point at which the new content becomes visible. Messages go to standard error with the program name, the operation and the object. The exit status is part of the interface. The one weakness is a variable declared after a goto that can jump past it, which is why the descriptors are declared before the first jump in a production version, and why a reviewer should check that no label releases something not yet acquired.

To test it, run it against /dev/full as the destination in a directory where you can create the temporary file, or under strace -P cpfile -e inject=write:error=ENOSPC as the earlier post showed, and check that the destination is untouched and the temporary file is gone. Those two checks are the proof that the error paths hold.

Where this guide does not fit

The advice here is for programs that run on a general-purpose operating system and return to a human or a supervisor. It fits less well in four places.

Embedded firmware without a heap or a filesystem. There may be no errno, no printf and no process to exit. Errors become status registers, fault handlers and watchdog resets, and the cluster of posts on embedded topics is the right place to look. The principles of checking every result and cleaning up on every path still apply, expressed in different mechanisms.

Kernel code. The kernel uses negative error numbers returned directly, goto cleanup chains with careful ordering and ERR_PTR conventions for returning errors in pointers, and it cannot print to a terminal. The kernel topic covers it.

Hard real-time systems. A retry loop with exponential back-off is wrong where deadlines are fixed, and the correct response to a fault may be a defined safe state in bounded time.

Throwaway scripts. A ten-line tool that fails with a stack trace is acceptable if no one depends on it. The cost-benefit changes the moment other programs call it.

A reading path through the cluster

If you are new, read in this order. Start with what errno is, then printing readable errors, then checking return values, then the common errno values. Continue with goto cleanup and strerror_r and the thread-local errno post. After that, read the post on non-blocking helpers, on matching man pages to strace, and on preserving errno. For other languages, choose the post for yours: Rust, Go, C++, Zig or Win32. Finish with raw syscall return values, the library design post and fault injection with strace. The posts on libc internals in the next section of this cluster explain the layer that implements these conventions.

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.