Thread-Local errno & Exit Paths

Calling printf() before saving errno overwrites real failure codes with ENOTTY, sloppy error branches leak descriptors, and calling _exit() drops buffered stdio bytes silently. You will master thread-local errno preservation, thread-safe strerror_r(), reverse LIFO goto unwinding, and ISO C exit() versus kernel _exit() termination.

20 minfree previewLinux 6.12C11glibc 2.39→ module 3 lab
What you'll learn
  • Capture thread-local errno into saved_errno immediately after -1 returns and format diagnostics via strerror_r().
  • Unwind multi-resource C acquisition chains in reverse LIFO order using leak-free goto out_* labels and cleanup guards.
  • Contrast exit() (atexit LIFO hooks + stdio flush) against immediate _exit() / _Exit() kernel termination.

Why Intervening Calls Clobber errno & _exit() Drops Output

Two bugs turn routine error-handling code into hours of misdirection. First, a daemon whose stdout is redirected to /var/log/service.log executes if (open("/etc/shadow", O_RDONLY) == -1) { printf("open failed\n"); perror("cause"); }—and logs cause: Inappropriate ioctl for device (ENOTTY) instead of Permission denied (EACCES)! Why? Because on its first write to redirected stdout, printf() calls isatty(1) (ioctl(1, TCGETS, ...)), which fails on a regular file with ENOTTY and overwrites errno before perror() runs! Second, a CLI helper stages printf("READY") without a newline and terminates via _exit(0)—leaving a 0-byte output file on disk even though $? is 0!

Reliable error handling and termination in systems C rest on three strict mechanisms: preserving thread-local errno before any intervening call, unwinding partially acquired resources in reverse Last-In-First-Out (LIFO) order via structured goto labels, and choosing deliberately between library exit() cleanup and immediate kernel _exit() termination.

note: Think of a cockpit master-caution lamp paired with a latched fault-code display, and a normal gate shutdown checklist versus an emergency fuel-cutoff lever. You read the fault register only after the caution lamp trips, and pulling emergency cutoff halts engines immediately without running cabin shutdown routines.

Where it stops working: Unlike a hardware fault lamp that stays latched until manually reset, calling another library function such as printf() can silently overwrite thread-local errno mid-handler.

definition (Thread-Local errno, strerror_r(), LIFO goto & _exit()): Thread-Local errno (*__errno_location()): Originally a single global int in early Unix, ISO C11 / POSIX <errno.h> defines errno as a modifiable lvalue backed by per-thread Thread-Local Storage (%fs: segment on x86-64; CP15 TPIDRURO on ARMv7) so concurrent threads never race on fault codes. strerror_r(err, buf, len) formats err into caller-supplied stack memory without shared static-buffer races. LIFO goto Unwinding releases N acquired resources in strict reverse order (R_N -> ... -> R_1), while _exit(status) (<unistd.h>) traps straight to kernel exit_group() without running user-space atexit() or stdio fflush().

One Layer Down: TLS Resolution, goto State Invariants & Exit Lifecycles

When a glibc wrapper sees %rax / r0 in [-4095, -1], it writes (int)(-ret) into *__errno_location(). Notice the two asymmetry rules: (1) a successful syscall (ret >= 0) never writes 0 into errno, and (2) cleanup calls (close(), free(), printf(), unlink()) may internally invoke syscalls that overwrite errno. Therefore, every error handler must follow the atomic three-step capture pattern: check ret == -1, copy int saved_errno = errno; on line 1 of the branch, and restore errno = saved_errno; before returning -1 to callers.

In functions acquiring k resources sequentially (R_1 = open, R_2 = mmap, R_3 = malloc), naive nested if blocks require k * (k - 1) / 2 duplicated cleanup calls (3 resources -> 3 error branches; 5 resources -> 10 error branches, virtually guaranteeing a descriptor leak!). Structured LIFO goto unwinding reduces cleanup to exactly k lines executed linearly from the jump target downward, governed by two mathematical invariants: initialize int rc = -1; before the first check (setting rc = 0; only after R_k succeeds), and initialize pointers/descriptors to NULL/-1 before any goto.

Mechanism / Error CodeNumeric / Header ContractExact Runtime Behavior
ENOENT (2) / EEXIST (17)<errno.h> path statusMissing file (no O_CREAT) / existing path (`O_CREAT \O_EXCL`)
EINTR (4) / EAGAIN (11)<errno.h> transient statusSignal interrupted blocked call / O_NONBLOCK channel not ready
EIO (5) / EBADF (9) / ENOSPC (28)<errno.h> I/O & handle faultsMedia I/O failure / invalid fd / out of storage blocks
EACCES (13) / EINVAL (22) / ESPIPE (29)<errno.h> permission & seekMode denied / invalid flag or < 0 offset / lseek on pipe
return n; / exit(status)<stdlib.h> user-space teardownRuns atexit() (LIFO), flushes FILE buffers, calls _exit()
_exit(status) / _Exit(status)<unistd.h> / <stdlib.h> trapImmediate kernel exit_group(status & 0xFF); drops user stdio buffers
fig_m03_l02_arch.svg — Preserving thread-local errno against intervening…

Figure 3.2. Preserving thread-local errno against intervening clobbers, unwinding resources in LIFO goto order, and contrasting exit() against _exit().

step_m03_l02.svg — Capture saved_errno immediately on -1, unwind partial…step 1/4
  1. Step 1. Initialize int rc = -1 and NULL/-1 sentinels up front so early goto jumps never mask errors or free garbage.
  2. Step 2. Snapshot int saved_errno = errno on line 1 of an error branch before printf() or close() can overwrite TLS errno.
  3. Step 3. Release R_k down to R_1 in reverse LIFO goto order and restore errno = saved_errno before returning -1.
  4. Step 4. Use return/exit() to run atexit() and flush stdio buffers, or _exit() to enter exit_group() immediately.

Figure 3.2b. Capture saved_errno immediately on -1, unwind partial resources in reverse LIFO order, and choose deliberately between buffered exit() and immediate _exit().

XSI vs GNU strerror_r() & Scope-Guard Cleanup Notes

Watch a subtle header portability detail on Linux: under #define _POSIX_C_SOURCE 200809L without _GNU_SOURCE, <string.h> exposes standard POSIX XSI int strerror_r(int errnum, char *buf, size_t buflen) (0 on success), whereas defining _GNU_SOURCE switches strerror_r() to a GNU-specific char * return signature that may return a static string literal without copying into buf! Keeping _POSIX_C_SOURCE 200809L in portable error-formatting modules guarantees the XSI int contract across Linux, BSD, and macOS.

Proving saved_errno Clobber Immunity, LIFO goto & exit() vs _exit()

Save errno_exit_lab.c below. Run as emit_exit or emit_uexit with stdout redirected to a file, printf("%s", "BUFFERED_13B!") leaves 13 bytes inside glibc's user-space stdout buffer: exit(EXIT_SUCCESS) runs atexit() (10 bytes) and flushes all 13 bytes, whereas _exit(EXIT_SUCCESS) enters exit_group(0) immediately (0 bytes on disk!). Run with zero arguments, ./errno_exit_lab reproduces the printf() ENOTTY clobber on live errno while proving saved_errno preserves ENOENT (2) for strerror_r(), and verifies reverse-order stage_lifo_probe() goto cleanup!

learner@ksa: ~/gl-c01/m03-l02
learner@ksa:~/gl-c01/m03-l02$ bat -H 24 -H 49 -H 64 -H 65 errno_exit_lab.c File: errno_exit_lab.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <unistd.h>        static const char *g_atexit_path = "/tmp/ksa_atexit_marker.tmp";        static void cleanup_handler(void) {        int flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC;        int mfd = open(g_atexit_path, flags, 0644);        if (mfd >= 0) {            ssize_t wr = write(mfd, "ATEXIT_RAN", 10U);            (void)wr;            (void)close(mfd);        }    }        static int stage_lifo_probe(int inject_fail, int *closed_order) {        int rc = -1;      int fd = open("/dev/null", O_RDONLY | O_CLOEXEC);        void *buf = NULL;        if (fd < 0) {            goto out;        }        buf = malloc(128U);        if (buf == NULL || inject_fail) {            int err_hold = inject_fail ? EPROTO : errno;            *closed_order = 1;            errno = err_hold;            goto out_buf;        }        rc = 0;    out_buf:        free(buf);        if (*closed_order == 1) {            *closed_order = 2;        }        {            int keep = errno;            (void)close(fd);            errno = keep;        }    out:        return rc;  }        int main(int argc, char *argv[]) {        if (argc > 1 && strcmp(argv[1], "emit_exit") == 0) {            (void)atexit(cleanup_handler);            printf("%s", "BUFFERED_13B!");            exit(EXIT_SUCCESS);        }        if (argc > 1 && strcmp(argv[1], "emit_uexit") == 0) {            printf("%s", "BUFFERED_13B!");            _exit(EXIT_SUCCESS);        }            const char *p_exit = "/tmp/ksa_stdio_exit.tmp";        const char *p_uexit = "/tmp/ksa_stdio_uexit.tmp";          errno = 0;        int bad_fd = open("/tmp/ksa_nonexistent_99182.cfg", O_RDONLY | O_CLOEXEC);        int saved_errno = errno;        char msg_buf[128];        int r_rc = strerror_r(saved_errno, msg_buf, sizeof(msg_buf));            int lifo_step = 0;        errno = 0;        int lifo_ok = (stage_lifo_probe(1, &lifo_step) == -1 &&                       errno == EPROTO && lifo_step == 2 &&                       stage_lifo_probe(0, &lifo_step) == 0);            struct stat st_exit, st_uexit, st_marker;        long long b_exit = (stat(p_exit, &st_exit) == 0)                           ? (long long)st_exit.st_size : -1LL;        long long b_uexit = (stat(p_uexit, &st_uexit) == 0)                            ? (long long)st_uexit.st_size : -1LL;        long long b_atexit = (stat(g_atexit_path, &st_marker) == 0)                             ? (long long)st_marker.st_size : 0LL;            (void)unlink(p_exit);        (void)unlink(p_uexit);        (void)unlink(g_atexit_path);            printf("bad_fd=%d saved_errno=%d is_enoent=%d msg_ok=%d lifo_ok=%d\n",               bad_fd, saved_errno, saved_errno == ENOENT && r_rc == 0,               strstr(msg_buf, "No such") != NULL, lifo_ok);        printf("exit_flushed_bytes=%lld uexit_flushed_bytes=%lld atexit=%lld\n",               b_exit, b_uexit, b_atexit);        return EXIT_SUCCESS;    }
  1. Initialize rc = -1 and buf = NULL up front so jumping to out_buf or out never leaks fd or returns 0 on failure.
  2. _exit(EXIT_SUCCESS) traps straight to exit_group(0), dropping the 13 unflushed bytes in stdout's Ring 3 FILE buffer.
  3. Capture saved_errno BEFORE any intervening call; strerror_r() formats ENOENT into caller stack memory thread-safely.

Comparing Flushed exit() vs Dropped _exit() Output

Compile errno_exit_lab, redirect emit_exit and emit_uexit into /tmp files, verify exit_flushed_bytes=13 vs uexit_flushed_bytes=0 and atexit=10, and confirm under strace that emit_uexit traps directly to exit_group(0).

learner@ksa: ~/gl-c01/m03-l02
learner@ksa:~/gl-c01/m03-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror errno_exit_lab.c -o errno_exit_lablearner@ksa:~/gl-c01/m03-l02rm -f /tmp/ksa_atexit_marker.tmplearner@ksa:~/gl-c01/m03-l02./errno_exit_lab emit_exit > /tmp/ksa_stdio_exit.tmplearner@ksa:~/gl-c01/m03-l02./errno_exit_lab emit_uexit > /tmp/ksa_stdio_uexit.tmplearner@ksa:~/gl-c01/m03-l02./errno_exit_labbad_fd=-1 saved_errno=2 is_enoent=1 msg_ok=1 lifo_ok=1exit_flushed_bytes=13 uexit_flushed_bytes=0 atexit=10learner@ksa:~/gl-c01/m03-l02strace -e trace=exit_group ./errno_exit_lab emit_uexit 2>&1 >/dev/null | grep -c 'exit_group(0)'1learner@ksa:~/gl-c01/m03-l02rm -f errno_exit_lablearner@ksa:~/gl-c01/m03-l02

Why Cleanup Ordering & User-Space Teardown Govern Reliability

Both emit_exit and emit_uexit ended at kernel exit_group(0) ($? == 0), yet only exit() walked the atexit() stack (atexit=10) and flushed stdout's user-space FILE buffer (13 bytes vs 0 bytes) before trapping! Meanwhile, inside stage_lifo_probe(), preserving int keep = errno; around close(fd) ensured cleanup calls could never clobber the root-cause EPROTO diagnostic returned to the caller.

Scope Boundary — Child _exit() After Failed execve(): Later: When spawning child processes in GL-C02, a fork() child whose execve() fails must call _exit(127) rather than exit(127)—otherwise the child flushes a second copy of its parent's inherited user-space stdio buffers!

Guided Practice: Refactoring a Leaky 3-Step Initializer to LIFO goto

A helper acquires fd1 = open(a, ...), fd2 = open(b, ...), and buf = malloc(4096), returning -1 directly on each error (if (fd2 < 0) return -1;—leaking fd1!):

  1. Step 1 (Order the reverse labels): Write the three bottom labels in strict reverse acquisition order (out_buf: freeing buf, out_fd2: closing fd2, out_fd1: closing fd1, out: returning rc), initializing int rc = -1; at the top.
  2. Step 2 (Preserve errno across close()): Save int err = errno; before jumping on failure and restore errno = err; right before return rc; so close(fd1) cannot overwrite the open(b) or malloc() error code.

Independent Practice: GCC __attribute__((cleanup)) RAII Scope Guard

Write a standalone C11 test cleanup_guard.c (-std=c11 -Wall -Wextra -Werror) defining static void auto_close_fd(int *fdp) { if (*fdp >= 0) { int e = errno; (void)close(*fdp); errno = e; *fdp = -1; } } attached via __attribute__((cleanup(auto_close_fd))) int fd = open(...). Verify via /proc/self/fdinfo/ or lowest-slot reuse in main() that returning early on an injected error closes fd automatically while preserving errno.

Common Production Pitfalls

warning: Symptom: An error branch if (open(p, O_RDONLY) == -1) { printf("Failed %s\n", p); perror("reason"); } prints reason: Inappropriate ioctl for device (ENOTTY) whenever stdout is redirected to a file! Root Cause: First-use printf() probes isatty(1) internally, which fails on regular files with ENOTTY and overwrites thread-local errno before perror() reads it. Fix: Save int saved_errno = errno; on the line immediately following open() == -1 and format saved_errno via strerror_r().

warning: Symptom: Initializing int rc = 0; at the top of a goto-cleanup function causes an early if (fd2 < 0) goto out_fd1; branch to return 0 (success) to its caller with uninitialized output pointers! Root Cause: Forgetting rc = -1 before jumping leaves the optimistic 0 value intact. Fix: Always initialize int rc = -1; at function entry and assign rc = 0; only on the final line before the cleanup labels.

Knowledge Check

quiz · 1 of 4

(Review from earlier lesson) After ssize_t n = read(fd, buf, 64);, when is a C11 program permitted to inspect errno?

quiz · 2 of 4

Which termination call bypasses atexit() handlers and drops unflushed user-space stdio FILE buffers by trapping directly into the Linux kernel?

quiz · 3 of 4

In a multithreaded Linux daemon compiled with #define _POSIX_C_SOURCE 200809L, which pattern safely formats a saved errno value without shared static-buffer races?

quiz · 4 of 4

A C function acquires open() -> mmap() -> malloc() and unwinds failures via numbered goto labels (goto out_buf; goto out_map; goto out_fd;). Which two initializations prevent the classic goto cleanup defects?

Key takeaways

  • Failed Linux kernel syscalls return -errno in registers; glibc wrappers store the positive code in thread-local errno (<errno.h>) and return -1.
  • Successful calls never reset errno to 0; check ret == -1 first, capture int saved_errno = errno; immediately, and format via perror() or thread-safe strerror_r().
  • Memorize core diagnostic codes: ENOENT (2), EINTR (4), EIO (5), EBADF (9), EAGAIN (11), EACCES (13), EEXIST (17), EINVAL (22), ENOSPC (28), and ESPIPE (29).
  • Unwind multi-resource C functions in reverse (LIFO) order via numbered goto labels (int rc = -1 and NULL/-1 initializers) while preserving errno across close().
  • return in main and exit() execute atexit() handlers (LIFO) and flush stdio streams, whereas _exit() / _Exit() trap straight to kernel exit_group().
  • Next, we return to on-disk extent allocation to engineer sparse hole files, measure st_size versus st_blocks * 512, and test the read/write cursor asymmetry of O_RDWR | O_APPEND.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure