learner@ksa:~/gl-c01$

>_ Kernel Systems Academy

Linux Systems I/O & Buffering in C

Embedded Linux, systems, and infrastructure C engineers

Outcome: Engineer crash-safe, race-free Linux C11 file and stream I/O software across raw POSIX descriptors, VFS open-file tables, atomic positional syscalls, and two-stage buffered stdio streams.

6 modules18 lessons6 labsLinux 6.12 · C11
  1. m01/ Series Orientation, Kernel Boundary & C Toolchain
  2. m02/ Core Unbuffered POSIX File I/O
  3. m03/ Kernel Open-File Internals, Errors & Sparse Files
  4. m04/ File Sharing, Atomic Operations & Descriptor Control
  5. m05/ Standard C Library (stdio) Streams & Formatted I/O
  6. m06/ Two-Layer I/O Buffering, Durability & Capstone Engine
GL-C01 · Linux Systems I/O & Buffering in C1/515

m01/

>_ Kernel Systems Academy

Series Orientation, Kernel Boundary & C Toolchain

Onboard into the 4-course Linux Systems C series across Ring 3 / Ring 0 hardware boundaries, master the 4-stage GCC/Make C11 toolchain and POSIX boundary types, and trace glibc wrappers, CRT startup, and errno diagnostics under strace.

  1. 1.1 Welcome to Linux Systems C
  2. 1.2 GCC Pipeline, Make & POSIX Types
  3. 1.3 Syscall Wrappers, CRT, errno & strace

lab → Multi-File C11 Static Archive & Syscall Boundary Tracer

GL-C01 · Linux Systems I/O & Buffering in C2/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Welcome to Linux Systems C

free preview20 min

What you'll learn

  • Compare bare-metal MMIO firmware, Ring 0 struct file_operations drivers, and Ring 3 C processes across fault isolation.
  • Map the seven Linux kernel subsystems and the linux-vdso.so.1 zero-trap fastpath across GL-C01 through GL-C04.
  • Compile and execute a strict ISO C11 sanity binary while separating Ring 3 RAM loops from Ring 0 syscall traps.
GL-C01 · Linux Systems I/O & Buffering in C3/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Systems C Needs a Hardware Kernel Boundary

  • Suppose an engineer ports a bare-metal microcontroller routine *(volatile uint32_t *)0x0209C000 = 1U; dir…
GL-C01 · Linux Systems I/O & Buffering in C4/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Systems C Needs a Hardware Kernel Boundary

  • Naive C code fails at this boundary for two complementary reasons.
GL-C01 · Linux Systems I/O & Buffering in C5/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Systems C Needs a Hardware Kernel Boundary

  • Welcome to GL-C01 (Linux Systems I/O & Buffering in C), the foundational first course of our four-c…
GL-C01 · Linux Systems I/O & Buffering in C6/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Systems C Needs a Hardware Kernel Boundary

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C7/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Mental model

note: Think of an airport security checkpoint separating the public terminal from the active runway tarmac. Travelers organize itineraries freely inside the public hall, but loading cargo onto an aircraft requires handing parcels through a guarded counter to badged ground crew.

Where it stops working: Unlike a physical counter staffed by separate people, a CPU system call switches privilege levels on the exact same processor core in nanoseconds via architectural trap registers.

GL-C01 · Linux Systems I/O & Buffering in C8/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Hardware Privilege Rings, Syscall Gate & vDSO

definition: Privilege Rings (Ring 3 / EL0 vs Ring 0 / EL1): Originating in Multics protection rings and enforced by the x86-64 Current Privilege Level (CPL) or ARM Exception Level (EL), user C processes execute in unprivileged Ring 3 (EL0) inside isolated virtual address spaces, whereas the Linux kernel executes in Ring 0 (EL1) with full MMU, interrupt, and MMIO authority. A System Call Gate (syscall on x86-64 System V ABI; svc #0 on ARMv7 AAPCS) switches privilege synchronously on the active core, while the Virtual Dynamic Shared Object (vDSO, linux-vdso.so.1) maps read-only kernel timekeeper pages into Ring 3 so clock_gettime() reads monotonic clocks with zero traps.

GL-C01 · Linux Systems I/O & Buffering in C9/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Why Systems C Needs a Hardware Kernel Boundary

fig_m01_l01_arch.svg

Figure 1.1a: Hardware privilege boundary — Ring 3 C helpers and linux-vdso.so.1 execute in user space, while system calls cross the ABI trap gate into the seven Ring 0 Linux kernel subsystems.

GL-C01 · Linux Systems I/O & Buffering in C10/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon

  • Why did *(volatile uint32_t *)0x0209C000 = 1U; crash main() with SIGSEGV instead of toggling a GPIO…
GL-C01 · Linux Systems I/O & Buffering in C11/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C12/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon

fig_m01_l01_vmem_mmu.svg

Figure 1.1b: Virtual vs physical memory — the CPU MMU translates identical virtual addresses in PID 410 and PID 411 to separate 4 KiB physical RAM frames while blocking raw Ring-3 MMIO pointers with SIGSEGV.

GL-C01 · Linux Systems I/O & Buffering in C13/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

One Layer Down: ABI Trap Registers, Seven Subsystems, and Latency Math

  • When a user-space C program invokes a system call, the CPU does not jump to an arbitrary kernel address.
GL-C01 · Linux Systems I/O & Buffering in C14/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

One Layer Down: ABI Trap Registers, Seven Subsystems, and Latency Math

  • Quantifying transition cost explains why systems C separates Ring 3 computation from Ring 0 traps.
GL-C01 · Linux Systems I/O & Buffering in C15/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

One Layer Down: ABI Trap Registers, Seven Subsystems, and Latency Math

Raw MMIO dereferences in Ring 3 fault immediately in the MMU (SIGSEGV), protecting sibling processes and silicon.

User-space C logic and kernel drivers meet strictly across the VFS system call boundary.

GL-C01 · Linux Systems I/O & Buffering in C16/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Benchmarking Ring 3 + vDSO vs Syscall Traps in ISO C11

  • Because POSIX abstracts files, pipes, sockets, and /dev nodes behind uniform integer descriptors, standar…
GL-C01 · Linux Systems I/O & Buffering in C17/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

hello_systems.c

learner@ksa: ~/gl-c01/m01-l01
learner@ksa:~/gl-c01/m01-l01$ bat hello_systems.c File: hello_systems.c    #define _GNU_SOURCE    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/syscall.h>    #include <time.h>    #include <unistd.h>        struct course_banner {        char code[8];        uint32_t magic;        uint16_t modules;    };
GL-C01 · Linux Systems I/O & Buffering in C18/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Benchmarking Ring 3 + vDSO vs Syscall Traps in ISO C11

learner@ksa: ~/gl-c01/m01-l01
learner@ksa:~/gl-c01/m01-l01gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror hello_systems.c -o hello_systemslearner@ksa:~/gl-c01/m01-l01./hello_systemslearner@ksa:~/gl-c01/m01-l01grep -q 'vdso' /proc/self/maps && echo vdso_mapped=1learner@ksa:~/gl-c01/m01-l01sh -c 'strace -e trace=clock_gettime ./hello_systems 2>&1 >/dev/null | grep -c "^clock_gettime" || true'learner@ksa:~/gl-c01/m01-l01strace -e trace=getpid ./hello_systems 2>&1 >/dev/null | grep -c '^getpid('learner@ksa:~/gl-c01/m01-l01rm -f hello_systemscourse=GL-C01 code_len=6 modules=6 u32_bytes=4 vmem_ok=1vdso_mapped=102000learner@ksa:~/gl-c01/m01-l01
GL-C01 · Linux Systems I/O & Buffering in C19/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Tracing the Execution Split, Pitfalls & Practice

  • Look closely at what ./hello_systems and strace just proved on Linux 6.12.
GL-C01 · Linux Systems I/O & Buffering in C20/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: An engineer runs strace ./daemon to verify whether monotonic timestamping is firing, sees zero clock_gettime lines, and falsely concludes the timer code was compiled out. Root Cause: On x86-64 and ARMv7 Linux, glibc resolves clock_gettime() and gettimeofday() through linux-vdso.so.1 (AT_SYSINFO_EHDR) in Ring 3 without executing syscall or svc #0, and strace only intercepts kernel privilege switches. Fix: Trace user-space library calls with ltrace or gdb breakpoints rather than strace whenever inspecting vDSO-accelerated routines.

GL-C01 · Linux Systems I/O & Buffering in C21/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: A legacy hardware diagnostic ported from bare-metal C dereferences (volatile uint32_t *)0x0209C000 inside main() and crashes immediately with SIGSEGV (exit code 139). Root Cause: Every pointer in a Linux user process is a Ring 3 virtual address translated by per-process page tables; unmapped physical bus addresses fault in the MMU before touching interconnect wires. Fix: Access hardware strictly through VFS character device nodes (/dev/gpiochip*, /dev/spidev*, /dev/i2c-*) backed by Ring 0 kernel drivers (Later: user-space peripheral buses are covered in GL-C04, and Ring 0 struct file_operations driver authoring is covered in GL-E04).

GL-C01 · Linux Systems I/O & Buffering in C22/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Guided Practice: Predicting Trap Counts Across Mixed Loops

  • Suppose you extend hello_systems.c with a loop of 500 iterations where each iteration calls `memcpy(dst…
GL-C01 · Linux Systems I/O & Buffering in C23/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Guided Practice: Predicting Trap Counts Across Mixed Loops

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C24/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Independent Practice: Trap-Amortization Breakeven Estimator

  • Write a standalone C11 program trap_budget.c compiled with -std=c11 -O2 -Wall -Wextra -Werror that meas…
GL-C01 · Linux Systems I/O & Buffering in C25/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

An embedded firmware engineer porting bare-metal MCU LED code to a Linux user-space daemon attempts to dereference physical GPIO register 0x0209C000 directly inside main(). What happens when the process runs?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C26/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

How do user-space C applications and Linux kernel character drivers cooperate when controlling a /dev/led0 device node?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C27/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

Why does GL-C01 open the four-course Linux Systems C series with VFS file descriptors and stdio buffering before IPC/sockets (GL-C03) or embedded peripherals (GL-C04)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C28/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Quick check

A latency benchmark calls clock_gettime(CLOCK_MONOTONIC, &ts) two thousand times, yet strace -e trace=clock_gettime ./bench prints 0 syscall lines when you review the trace. Which mechanism accounts for this observation?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C29/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Summary

  • GL-C01 opens the 4-course Linux Systems Programming in C series by establishing the toolchain, VFS descriptor, and stdio buffering foundation used across filesystems, IPC, sockets, and /dev peripherals.
  • Bare-metal firmware mixes user logic and raw MMIO register writes in one flat address space, whereas Linux isolates Ring 3 / EL0 user processes from Ring 0 / EL1 struct file_operations drivers via the MMU.
  • Standard system calls cross from Ring 3 / EL0 user mode into Ring 0 / EL1 Linux kernel mode via synchronous CPU traps across seven core subsystems, while linux-vdso.so.1 (AT_SYSINFO_EHDR) serves clock_gettime() from a read-only shared page with zero traps.
  • Standard user-space C code compiles cleanly across x86-64 workstations and embedded ARMv7 targets when built with strict -std=c11 -Wall -Wextra -Werror discipline.
GL-C01 · Linux Systems I/O & Buffering in C30/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Summary

  • Next, before invoking raw Linux kernel descriptors directly, we will dissect the four-stage GCC and static-…
GL-C01 · Linux Systems I/O & Buffering in C31/515

GL-C01 · 1.1 (m01-l01)

>_ Kernel Systems Academy

Key takeaways

  • Standard system calls cross from Ring 3 / EL0 user mode into Ring 0 / EL1 Linux kernel mode via synchronous CPU traps across seven core subsystems, while linux-vdso.so.1 (AT_SYSINFO_EHDR) serves clock_gettime() from a read-only shared page with zero traps.
  • Standard user-space C code compiles cleanly across x86-64 workstations and embedded ARMv7 targets when built with strict -std=c11 -Wall -Wextra -Werror discipline.
  • Next, before invoking raw Linux kernel descriptors directly, we will dissect the four-stage GCC and static-archive build pipeline, POSIX feature-test macros, boundary integer types, and ISO C11 Undefined Behavior defenses.
GL-C01 · Linux Systems I/O & Buffering in C32/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

GCC Pipeline, Make & POSIX Types

free preview20 min

What you'll learn

  • Build multi-file ISO C11 targets across GCC stages (-E, -S, -c, ar rcs, link) with -Wall -Wextra -Werror.
  • Configure _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 before headers using man 2 and man 3 interface contracts.
  • Audit C11 code for Undefined Behavior, -fno-common collisions, size_t/ssize_t wraparound, and octal 0644 bugs.
GL-C01 · Linux Systems I/O & Buffering in C33/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Why Sloppy C Types and Opaque Builds Break Systems Software

  • Consider a network packet validator written as if (payload_len + 16 < payload_len) return -1; where `payl…
GL-C01 · Linux Systems I/O & Buffering in C34/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Why Sloppy C Types and Opaque Builds Break Systems Software

  • Naive C habits fail because developers conflate hardware assembly behavior with the abstract machine specif…
GL-C01 · Linux Systems I/O & Buffering in C35/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Mental model

note: Think of a precision machine shop with an assembly blueprint, calipers calibrated in millimeters versus signed tolerances, and standardized part bins. Reading the wrong scale or skipping the torque specification produces parts that look close on the bench and shear under load.

Where it stops working: Unlike physical tolerances that degrade gradually, mixing unsigned size_t with signed ssize_t -1 or decimal 644 with octal 0644 flips exact bits instantaneously.

GL-C01 · Linux Systems I/O & Buffering in C36/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Four-Stage GCC Pipeline, Feature Macros & C11 UB

definition: Four-Stage Translation Pipeline & Tentative Definitions: Originating in early Unix cpp -> cc1 -> as -> ld passes, GCC lowers ISO C11 source across preprocessing (-E -> .i), compilation (-S -> .s), assembly (-c -> relocatable Executable and Linkable Format .o), and linking (ar rcs static .a archives or -fPIC -shared .so objects). Feature-Test Macros (_POSIX_C_SOURCE, named by IEEE 1003.1 to gate namespace exposure) unlock POSIX declarations above ISO C11, while Undefined Behavior (UB, C11 §3.4.3) designates operations—such as signed overflow or strict-aliasing violations—for which the standard imposes zero requirements.

GL-C01 · Linux Systems I/O & Buffering in C37/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

One Layer Down: ELF Object Sections, Alignment Math & Link Order

  • Across Stage 3 (gcc -c), the assembler partitions each relocatable .o file into distinct ELF sections:…
GL-C01 · Linux Systems I/O & Buffering in C38/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

One Layer Down: ELF Object Sections, Alignment Math & Link Order

  • Struct layout and boundary sizing obey exact binary alignment arithmetic.
GL-C01 · Linux Systems I/O & Buffering in C39/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

One Layer Down: ELF Object Sections, Alignment Math & Link Order

fig_m01_l02_arch.svg

Figure 1.2: Four-stage GCC/archive builds, struct padded_hdr byte-alignment math, and signed/unsigned POSIX boundary contracts.

GL-C01 · Linux Systems I/O & Buffering in C40/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

One Layer Down: ELF Object Sections, Alignment Math & Link Order

Stage 1 (-E) — Define _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 on lines 1..2 before any header is included.

Feature-test macros, strict C11 warning/sanitizer flags, and single-pass archive link ordering eliminate silent type and symbol bugs at build time.

GL-C01 · Linux Systems I/O & Buffering in C41/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Feature-Test Macros,Incremental Make & Sanitizer Flags

  • Under strict -std=c11, GCC defines __STRICT_ANSI__ and hides POSIX symbols (fileno, pread, `fdatasy…
GL-C01 · Linux Systems I/O & Buffering in C42/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Makefile

learner@ksa: ~/gl-c01/m01-l02
learner@ksa:~/gl-c01/m01-l02$ bat Makefile File: Makefile    CC     := gcc    CFLAGS := -std=c11 -Wall -Wextra -Werror -MMD -MP -g -O2    SAN    := -fsanitize=address,undefined -fno-omit-frame-pointer        .PHONY: all sanitize clean    all: inspector        libsysbuf.a: sysbuf.o    	ar rcs $@ $^        inspector: inspector.o libsysbuf.a    	$(CC) $(CFLAGS) inspector.o -L. -lsysbuf -o $@        sanitize: sysbuf.c inspector.c
GL-C01 · Linux Systems I/O & Buffering in C43/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Auditing Binary Frames, Struct Padding, Strict Aliasing & Octal Modes

  • Save type_bridge.c below.
GL-C01 · Linux Systems I/O & Buffering in C44/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

type_bridge.c

learner@ksa: ~/gl-c01/m01-l02
learner@ksa:~/gl-c01/m01-l02$ bat type_bridge.c File: type_bridge.c    #define _FILE_OFFSET_BITS 64    #define _POSIX_C_SOURCE 200809L    #include <stdalign.h>    #include <stddef.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <sys/types.h>        struct padded_hdr {        uint8_t tag;        uint32_t seq;
GL-C01 · Linux Systems I/O & Buffering in C45/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Stepping Through All Four GCC Stages, nm & Sanitizers

  • Execute all four GCC translation stages (-E, -S, -c, and final link with `-fsanitize=address,undefine…
GL-C01 · Linux Systems I/O & Buffering in C46/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Stepping Through All Four GCC Stages, nm & Sanitizers

learner@ksa: ~/gl-c01/m01-l02
learner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -E type_bridge.c -o type_bridge.ilearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -S type_bridge.c -o type_bridge.slearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -c type_bridge.c -o type_bridge.olearner@ksa:~/gl-c01/m01-l02nm type_bridge.o | grep -c ' T main$'learner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror -fsanitize=address,undefined type_bridge.c -o type_bridgelearner@ksa:~/gl-c01/m01-l02./type_bridge && rm -f type_bridge.i type_bridge.s type_bridge.o type_bridge1arr_sizeof=16 strlen_at_nul=2 ptr_decayed=1 ovf_guard=1ssize_signed=1 off_bits=64 oct_0644=420 dec_644_oct=01204hdr_sz=12 seq_off=4 align=4 f32_hex=0x3f800000learner@ksa:~/gl-c01/m01-l02
GL-C01 · Linux Systems I/O & Buffering in C47/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Why Strict Types, Visibility & Sanitizers Catch Silent Corruption

  • Stepping across .i -> .s -> .o -> ELF proved each layer's contract empirically.
GL-C01 · Linux Systems I/O & Buffering in C48/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Guided Practice: Reordering Struct Fields & Fixing Aliasing UB

  • Examine struct padded_hdr (12 bytes: uint8_t tag; uint32_t seq; uint16_t flags;) and the broken stric…
GL-C01 · Linux Systems I/O & Buffering in C49/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Guided Practice: Reordering Struct Fields & Fixing Aliasing UB

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C50/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Independent Practice: Static Archive Link-Order & -fno-common Audit

  • Create three files (frame.h, frame.c, driver_cli.c) where frame.h declares `extern size_t g_frames_…
GL-C01 · Linux Systems I/O & Buffering in C51/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: GCC rejects fileno(), pread(), or strnlen() with implicit declaration of function under -std=c11 -Werror even though #define _POSIX_C_SOURCE 200809L is present in the .c file. Root Cause: A project header (such as #include "config.h") included <stdio.h> above the #define, freezing <features.h> in strict ISO C11 mode for the rest of the translation unit. Fix: Place #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 on lines 1–2 of every .c file (or pass -D_POSIX_C_SOURCE=200809L -D_FILE_OFFSET_BITS=64 in CFLAGS).

GL-C01 · Linux Systems I/O & Buffering in C52/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: A length guard if (signed_len + hdr_sz < signed_len) return -1; passes -Wall -Wextra cleanly yet allows heap corruption at -O2, or int status; inside common.h triggers multiple definition of 'status' on GCC 13. Root Cause: Signed integer overflow is ISO C11 Undefined Behavior so -O2 folds a + 16 < a to false, and GCC 10+ defaults to -fno-common so tentative definitions in headers emit colliding .bss globals. Fix: Validate capacities via unsigned size_t subtraction (if (len > cap - hdr_sz)), and declare extern int status; in headers with exactly one .c definition.

GL-C01 · Linux Systems I/O & Buffering in C53/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

You need the authoritative header requirements, return contract, and error codes for the Linux kernel write() system call rather than the user terminal messaging utility. Which command opens the right manual section?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C54/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) Why does compiling with gcc -c sysbuf.c -o sysbuf.o succeed even when sysbuf.c defines Ring 3 helper functions without defining main()?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C55/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

What permission bitmask is produced in C if a developer writes mode_t m = 644; instead of mode_t m = 0644;?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C56/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Quick check

A packet parser validates int payload_len (>= 0) with if (payload_len + 16 < payload_len) return -1; before malloc((size_t)(payload_len + 16)). Why does gcc -std=c11 -O2 delete that guard when you review the generated .s assembly?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C57/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Summary

  • Compile multi-file systems C projects explicitly across preprocessing (-E), compilation (-S), assembly (-c), archiving (ar rcs), and linking with -std=c11 -Wall -Wextra -Werror and -fsanitize=address,undefined.
  • Define feature-test macros (_POSIX_C_SOURCE 200809L, _FILE_OFFSET_BITS 64) before the very first #include, and use extern declarations in headers so GCC -fno-common never hits tentative-definition collisions.
  • Consult man 2 for Linux kernel syscalls and man 3 for glibc functions, verifying SYNOPSIS, RETURN VALUE, and ERRORS before writing callers.
  • Pair unsigned size_t capacities with signed ssize_t / off_t return checks, pass (const uint8_t *, len) for binary data, write octal 0644 permissions, and replace signed-overflow or pointer-aliasing UB with unsigned subtraction and memcpy().
GL-C01 · Linux Systems I/O & Buffering in C58/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Summary

  • Next, we will link C11 translation units against glibc (libc.so.6), trace dynamic .plt/.got.plt rel…
GL-C01 · Linux Systems I/O & Buffering in C59/515

GL-C01 · 1.2 (m01-l02)

>_ Kernel Systems Academy

Key takeaways

  • Consult man 2 for Linux kernel syscalls and man 3 for glibc functions, verifying SYNOPSIS, RETURN VALUE, and ERRORS before writing callers.
  • Pair unsigned size_t capacities with signed ssize_t / off_t return checks, pass (const uint8_t *, len) for binary data, write octal 0644 permissions, and replace signed-overflow or pointer-aliasing UB with unsigned subtraction and memcpy().
  • Next, we will link C11 translation units against glibc (libc.so.6), trace dynamic .plt/.got.plt relocations and C Runtime (CRT) _start initialization, inspect errno, and count exact traps under strace.
GL-C01 · Linux Systems I/O & Buffering in C60/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Syscall Wrappers, CRT, errno & strace

free preview20 minlab lab_m01_toolchain_tracer

What you'll learn

  • Distinguish pure Ring 3 glibc helpers (strlen, memcpy) from Ring 0 syscall wrappers and .plt/.got.plt stubs.
  • Trace ELF startup from PT_INTERP and CRT _start -> __libc_start_main -> main() across descriptors 0, 1, 2.
  • Diagnose negative kernel -errno translations via thread-local errno, perror(), and strerror() (EBADF, EINTR).
GL-C01 · Linux Systems I/O & Buffering in C61/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Why main() Is Not First and Not Every libc Call Enters Ring 0

  • Two mysteries ambush almost every engineer debugging a deployed Linux binary for the first time.
GL-C01 · Linux Systems I/O & Buffering in C62/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Why main() Is Not First and Not Every libc Call Enters Ring 0

  • Both failures stem from treating main() and <stdio.h>/<unistd.h> as black boxes.
GL-C01 · Linux Systems I/O & Buffering in C63/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Mental model

note: Think of a corporate mailroom inside your office building. Drafting memos or sorting spreadsheets happens right at your desk, whereas sending a registered courier pouch goes through a mailroom clerk who stamps the manifest, hands it to external transport, and records any delivery rejection code on your receipt.

Where it stops working: Unlike an office clerk who works asynchronously, a glibc syscall wrapper executes synchronously on the calling thread's stack and CPU registers before returning control.

GL-C01 · Linux Systems I/O & Buffering in C64/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

CRT Startup, PLT/GOT Trampolines & Syscall Wrappers

definition: C Runtime Startup (crt1.o _start) & Dynamic Linkage (.plt / .got.plt): Named for the C Runtime object linked ahead of user .o files, _start aligns the initial stack pointer pushed by execve() (argc, argv[], envp[], and Elf_auxv_t auxiliary vectors) and calls __libc_start_main(). In Position-Independent Executables (PIE), external calls jump through a read-only Procedure Linkage Table (.plt) stub that dereferences a Global Offset Table (.got.plt) JUMP_SLOT resolved by the PT_INTERP dynamic linker (ld-linux). Syscall Wrappers issue the CPU trap and translate kernel returns in [-4095, -1] into positive thread-local errno plus (ssize_t)-1.

GL-C01 · Linux Systems I/O & Buffering in C65/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch

  • During execve(), the Linux kernel ELF loader maps .text (PROT_READ | PROT_EXEC), .rodata (`PROT_REA…
GL-C01 · Linux Systems I/O & Buffering in C66/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch

  • Why does the Linux kernel reserve [-4095, -1] (0xfffffffffffff001..0xffffffffffffffff on 64-bit) in `%r…
GL-C01 · Linux Systems I/O & Buffering in C67/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch

fig_m01_l03_arch.svg

Figure 1.3: ELF PT_INTERP and crt1.o _start startup chain, PLT/GOT dynamic linkage, and [-4095, -1] thread-local errno demultiplexing.

GL-C01 · Linux Systems I/O & Buffering in C68/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

One Layer Down: execve Stack Layout, -4095..-1 Error Math & PLT Dispatch

execve() builds the 16-byte aligned stack (argc, argv, envp, auxv) and loads PT_INTERP (missing loader => ENOENT).

Execution starts in PT_INTERP and crt1.o _start before main(), and only Ring 0 syscall wrappers enter strace or set thread-local errno on failure.

GL-C01 · Linux Systems I/O & Buffering in C69/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Inspecting Standard Descriptors, GOT/PLT Relocations & errno

  • Include <unistd.h>, <errno.h>, <stdio.h>, and <string.h> under #define _POSIX_C_SOURCE 200809L.
GL-C01 · Linux Systems I/O & Buffering in C70/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Probing .init_array Constructors, Pure Loops, EBADF & strace

  • Save crt_wrapper_probe.c below.
GL-C01 · Linux Systems I/O & Buffering in C71/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

crt_wrapper_probe.c

learner@ksa: ~/gl-c01/m01-l03
learner@ksa:~/gl-c01/m01-l03$ bat crt_wrapper_probe.c File: crt_wrapper_probe.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <gnu/libc-version.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <unistd.h>        static int g_ctor_ran = 0;        __attribute__((constructor))    static void on_crt_init(void) {        g_ctor_ran = 1;    }
GL-C01 · Linux Systems I/O & Buffering in C72/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1

  • Compile crt_wrapper_probe, verify PT_INTERP and write's .got.plt JUMP_SLOT relocation with `reade…
GL-C01 · Linux Systems I/O & Buffering in C73/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1

learner@ksa: ~/gl-c01/m01-l03
learner@ksa:~/gl-c01/m01-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror crt_wrapper_probe.c -o crt_wrapper_probelearner@ksa:~/gl-c01/m01-l03./crt_wrapper_probe frame-07 && echo exit_status=$?learner@ksa:~/gl-c01/m01-l03ldd ./crt_wrapper_probe | grep -o 'libc\.so\.6' | head -n 1learner@ksa:~/gl-c01/m01-l03readelf -lW ./crt_wrapper_probe | grep -c 'Requesting program interpreter'learner@ksa:~/gl-c01/m01-l03readelf -rW ./crt_wrapper_probe | grep -c 'JUMP_SLOT.*write'learner@ksa:~/gl-c01/m01-l03strace -e trace=write ./crt_wrapper_probe frame-07 2>&1 >/dev/null | grep -c '^write('glibc=2.39 ctor=1 argc=2 pure_acc=8000 argv_null=1 ebadf_ok=1exit_status=0libc.so.6112learner@ksa:~/gl-c01/m01-l03
GL-C01 · Linux Systems I/O & Buffering in C74/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1

  • Inspect the recorded strace session: ld-linux maps /etc/ld.so.cache and libc.so.6 first, the `1,000…
GL-C01 · Linux Systems I/O & Buffering in C75/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Verifying PT_INTERP, JUMP_SLOT Relocations, strace & Lab 1

strace — learner@ksa: ~/gl-c01/m01-l03
learner@ksa:~/gl-c01/m01-l03strace -e trace=openat,write,close ./crt_wrapper_probe frame-07
GL-C01 · Linux Systems I/O & Buffering in C76/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Lab: lab_m01_toolchain_tracer

  • 1.

Verify: ./check.sh exits 0.

GL-C01 · Linux Systems I/O & Buffering in C77/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Tracing Control from PT_INTERP and _start to $?

  • When the shell invoked ./crt_wrapper_probe frame-07, execve() loaded PT_INTERP, mapped libc.so.6, a…
GL-C01 · Linux Systems I/O & Buffering in C78/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Guided Practice: Link-Time Fault Injection with -Wl,--wrap=write

  • GNU ld's --wrap=write flag redirects calls to write() to __wrap_write() while exposing the real wra…
GL-C01 · Linux Systems I/O & Buffering in C79/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Guided Practice: Link-Time Fault Injection with -Wl,--wrap=write

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C80/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Independent Practice: Auxiliary Vector (auxv) Hardware & Page-Size Inspector

  • Write a standalone C11 binary auxv_probe.c (-std=c11 -Wall -Wextra -Werror) that calls `getauxval(AT_PA…
GL-C01 · Linux Systems I/O & Buffering in C81/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: A helper runs ssize_t n = write(fd, buf, len); if (errno != 0) log_fatal(errno); and aborts with a stale "Bad file descriptor" error even when n == (ssize_t)len. Root Cause: Successful POSIX syscall wrappers never reset errno back to 0; errno retains whatever nonzero code an earlier failed probe left behind. Fix: Check errno strictly inside if (n == -1) (and save int saved_err = errno; before any logging call).

GL-C01 · Linux Systems I/O & Buffering in C82/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Running ./crt_wrapper_probe with zero CLI arguments crashes with SIGSEGV at strlen(argv[1]), or returning -1 from main() reports 255 in shell $?. Root Cause: With no CLI arguments, argc == 1 and argv[1] == NULL; meanwhile, POSIX waitpid() / exit_group() masks exit codes to status & 0xFF (-1 & 0xFF == 255). Fix: Check argc > idx before dereferencing argv[idx], and return EXIT_SUCCESS (0) or documented positive exit codes (1..125).

GL-C01 · Linux Systems I/O & Buffering in C83/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

While profiling a binary packet parser under strace, you observe write() traps in the trace output, but zero lines for strlen(), memcpy(), or snprintf(). Why?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C84/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) A write(fd, buf, len) call fails because fd was -1. What values do the Linux kernel trap return register and the user-space glibc wrapper produce respectively?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C85/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

Which routine executes as the ELF entry point before main(int argc, char *argv[]) and guarantees argv[argc] == NULL?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C86/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Quick check

You copy a cross-compiled ./sensor_agent ELF executable onto a minimal ARMv7 rootfs, verify ls -l ./sensor_agent shows -rwxr-xr-x, yet running ./sensor_agent prints execve: No such file or directory (ENOENT). What is missing when you review the binary with readelf -lW?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C87/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Summary

  • glibc (libc.so.6) separates pure Ring 3 memory/string helpers (strlen(), memcpy(), snprintf()) from Ring 0 syscall wrappers (write(), read(), openat()) routed through .plt / .got.plt JUMP_SLOT relocations and PT_INTERP.
  • Every POSIX process inherits STDIN_FILENO (0), STDOUT_FILENO (1), and STDERR_FILENO (2) open at startup.
  • When a syscall fails, the Linux kernel returns -errno in [-4095, -1] and the glibc wrapper sets positive thread-local errno (EBADF, EINTR, formatted via perror() / strerror()) and returns -1.
  • ELF binaries enter at _start (crt1.o) -> __libc_start_main() with argc, argv[], envp[], and Elf_auxv_t on the initial stack, executing .init_array constructors before main() and forwarding status & 0xFF to $?.
GL-C01 · Linux Systems I/O & Buffering in C88/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Summary

  • With toolchain, ELF startup, errno, and strace mastered, Module 2 opens disk files directly to control…
GL-C01 · Linux Systems I/O & Buffering in C89/515

GL-C01 · 1.3 (m01-l03)

>_ Kernel Systems Academy

Key takeaways

  • When a syscall fails, the Linux kernel returns -errno in [-4095, -1] and the glibc wrapper sets positive thread-local errno (EBADF, EINTR, formatted via perror() / strerror()) and returns -1.
  • ELF binaries enter at _start (crt1.o) -> __libc_start_main() with argc, argv[], envp[], and Elf_auxv_t on the initial stack, executing .init_array constructors before main() and forwarding status & 0xFF to $?.
  • With toolchain, ELF startup, errno, and strace mastered, Module 2 opens disk files directly to control per-process descriptor allocation, open() bitmasks, and mode & ~umask permissions.
GL-C01 · Linux Systems I/O & Buffering in C90/515

m02/

>_ Kernel Systems Academy

Core Unbuffered POSIX File I/O

Acquire and manage per-process file descriptors with exact open() flags and mode & ~umask permissions, build partial-count and EINTR-resilient read_full() and write_all() loops, and implement side-effect-safe lseek() byte-slicing tools.

  1. 2.1 Descriptors, open Flags & Permissions
  2. 2.2 Byte I/O with write, read & close
  3. 2.3 File Offsets & lseek Slicing

lab → Byte-Exact Framed Slice Copier

GL-C01 · Linux Systems I/O & Buffering in C91/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Descriptors, open Flags & Permissions

free preview20 min

What you'll learn

  • Verify lowest-unused descriptor allocation across 0..2, slot reuse after close(), and dentry removal via unlink().
  • Select open() O_ACCMODE modes and O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_CLOEXEC, and O_TMPFILE flags.
  • Derive creation permissions via mode & ~umask and UB-free unsigned shifts (1U << bit) without variadic stack bugs.
GL-C01 · Linux Systems I/O & Buffering in C92/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Why Naive open() Calls Leak Handles, Corrupt Modes & Trigger UB

  • Picture a background daemon that closes STDIN_FILENO (0), STDOUT_FILENO (1), and STDERR_FILENO (`…
GL-C01 · Linux Systems I/O & Buffering in C93/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Why Naive open() Calls Leak Handles, Corrupt Modes & Trigger UB

  • Naive code stumbles on open() because C lacks function overloading (forcing <fcntl.h> to declare `open(…
GL-C01 · Linux Systems I/O & Buffering in C94/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Mental model

note: Think of a numbered coat-check rack with brass tags 0 through 1023. Slots 0, 1, and 2 are pre-hung at shift start, every new coat claims the lowest empty hook, and returning a tag immediately frees that hook for the next guest.

Where it stops working: Unlike brass coat tags, an open file descriptor also carries kernel access-mode and close-on-exec flags enforced on every subsequent read, write, or execve call.

GL-C01 · Linux Systems I/O & Buffering in C95/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

File Descriptors, O_ACCMODE & Process umask

definition: File Descriptor (fd) & Lowest-Unused Allocation: Coined in Seventh Edition Unix for a non-negative int array index into a process's private files_struct descriptor table (0..RLIMIT_NOFILE - 1), POSIX mandates that open() and openat() allocate the lowest-numbered unused slot (returning -1 with EMFILE when full). Access Mode (O_ACCMODE) is a 2-bit field (03 octal: O_RDONLY = 0, O_WRONLY = 1, O_RDWR = 2), while User File-Creation Mask (umask) clears disallowed permission bits on O_CREAT / O_TMPFILE via effective_mode = mode & ~umask.

GL-C01 · Linux Systems I/O & Buffering in C96/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts

  • Inside the Linux kernel (fs/file.c), __alloc_fd() locates the lowest free descriptor in O(1) amortize…
GL-C01 · Linux Systems I/O & Buffering in C97/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts

  • When O_CREAT or O_TMPFILE creates a new inode, VFS combines the 4-bit file type (S_IFREG = 0100000) w…
GL-C01 · Linux Systems I/O & Buffering in C98/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts

fig_m02_l01_flags.svg

Figure 2.1a: Per-process descriptor table lowest-slot allocation and open() flag composition.

GL-C01 · Linux Systems I/O & Buffering in C99/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts

fig_m02_l01_arch.svg

Figure 2.1b: Kernel fdtable O(1) bitmap scan and 16-bit POSIX mode_t / ~umask bitfield algebra.

GL-C01 · Linux Systems I/O & Buffering in C100/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts

Compose one O_ACCMODE access value with O_CREAT | O_EXCL | O_CLOEXEC and an explicit octal mode_t.

Every open() claims the lowest unused fdtable slot, seals FD_CLOEXEC atomically when O_CLOEXEC is passed, and masks new inode permissions by ~umask.

GL-C01 · Linux Systems I/O & Buffering in C101/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Variadic open() Prototypes, openat() & unlink()

  • Include <fcntl.h>, <sys/stat.h>, <sys/types.h>, and <unistd.h> under `#define _POSIX_C_SOURCE 20080…
GL-C01 · Linux Systems I/O & Buffering in C102/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

open

open(2) at a glance — GL-C01
open(2)                     GL-C01 Quick Reference                     open(2) NAME       open, openat - open or create a file and allocate a descriptor SYNOPSIS       #include <fcntl.h>       int open(const char *pathname, int flags, ... /* mode_t mode */);       int openat(int dirfd, const char *pathname, int flags, ...); STANDARDS       POSIX.1-2008; openat() requires _POSIX_C_SOURCE >= 200809L. RETURN VALUE       Returns lowest-numbered unused descriptor (>= 0), or -1 with errno set. ERRORS       EACCES Requested access mode or directory search permission denied.       EEXIST O_CREAT | O_EXCL specified and pathname already exists.        EINTR  Blocked open on a slow device or FIFO interrupted by signal. Kernel Systems Academy                     m02-l01                     open(2) GL-C01 quick reference · full manual page: man 2 open 
GL-C01 · Linux Systems I/O & Buffering in C103/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Auditing Lowest-Slot Reuse, O_ACCMODE, umask & UB-Free Rotates

  • Save open_perm_audit.c below.
GL-C01 · Linux Systems I/O & Buffering in C104/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

open_perm_audit.c

learner@ksa: ~/gl-c01/m02-l01
learner@ksa:~/gl-c01/m02-l01$ bat open_perm_audit.c File: open_perm_audit.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <sys/stat.h>    #include <sys/types.h>    #include <unistd.h>        static inline uint32_t rotl32_safe(uint32_t x, unsigned int n) {        return (x << (n & 31U)) | (x >> ((-n) & 31U));    }
GL-C01 · Linux Systems I/O & Buffering in C105/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Verifying Descriptor Slots and Masked Inode Permissions

  • Compile open_perm_audit under -fsanitize=undefined, verify the runtime invariants, inspect the effectiv…
GL-C01 · Linux Systems I/O & Buffering in C106/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Verifying Descriptor Slots and Masked Inode Permissions

learner@ksa: ~/gl-c01/m02-l01
learner@ksa:~/gl-c01/m02-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -fsanitize=undefined open_perm_audit.c -o open_perm_auditlearner@ksa:~/gl-c01/m02-l01./open_perm_auditlearner@ksa:~/gl-c01/m02-l01echo "$(stat -c '%a' /tmp/ksa_m02_a.tmp) $(stat -c '%a' /tmp/ksa_m02_b.tmp)" && rm -f /tmp/ksa_m02_a.tmp /tmp/ksa_m02_b.tmp open_perm_auditstd_fds=0,1,2 consecutive=1 reused_lowest=1excl_eexist=1 unlink_ok=1 rot_ub_safe=1644 644learner@ksa:~/gl-c01/m02-l01
GL-C01 · Linux Systems I/O & Buffering in C107/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Tracing Bitmap Reuse, O_ACCMODE & umask Enforcement

  • Every check in open_perm_audit confirmed the VFS descriptor contract: fd1 and fd2 claimed consecutive…
GL-C01 · Linux Systems I/O & Buffering in C108/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Guided Practice: Exact Private Keyfile Creation Under Loose umask

  • Suppose an administrator runs your key-provisioning tool in a shell whose umask is 0000 (clearing zero…
GL-C01 · Linux Systems I/O & Buffering in C109/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Guided Practice: Exact Private Keyfile Creation Under Loose umask

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C110/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Independent Practice: Descriptor-Leak Exhaustion (EMFILE) Probe

  • Write a C11 diagnostic emfile_probe.c that lowers the process's soft RLIMIT_NOFILE ceiling to 16 insi…
GL-C01 · Linux Systems I/O & Buffering in C111/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: Newly created log files appear on disk with random permissions like --w-r-xr-T (01252) that change from run to run! Root Cause: Calling variadic open(path, O_WRONLY | O_CREAT) with two arguments causes the kernel wrapper to read uninitialized ABI register %rdx / r2 garbage as mode_t mode. Fix: Always pass an explicit octal mode (0644 or 0600) whenever flags includes O_CREAT or O_TMPFILE.

GL-C01 · Linux Systems I/O & Buffering in C112/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: Writing if (flags & O_RDONLY) to verify read-only access evaluates to 0 (false) on every descriptor in the system! Root Cause: On Linux and POSIX, O_RDONLY has integer value 0 (O_WRONLY == 1, O_RDWR == 2), so bitwise AND with 0 always yields 0. Fix: Mask the 2-bit access field with (flags & O_ACCMODE) == O_RDONLY.

GL-C01 · Linux Systems I/O & Buffering in C113/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

A process starts with standard descriptors 0, 1, and 2 open, calls close(0) to close standard input, and immediately calls open("/etc/hostname", O_RDONLY | O_CLOEXEC). Which integer descriptor does open() return?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C114/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

(Review from previous module) If a process running with umask 0027 calls open("key.bin", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH), what effective octal mode is stored on the new inode?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C115/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

Why do production Linux C services include O_CLOEXEC directly inside open() rather than calling fcntl(fd, F_SETFD, FD_CLOEXEC) on the next line?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C116/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Quick check

A framing header defines #define HDR_URGENT (1 << 31) and uint32_t rot(uint32_t x, unsigned int n) { return (x << n) | (x >> (32 - n)); }. Why does -fsanitize=undefined abort on HDR_URGENT and rot(v, 0U)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C117/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Summary

  • Every process indexes open VFS objects through non-negative int file descriptors (0..RLIMIT_NOFILE - 1), pre-opening 0, 1, and 2 and always allocating the lowest unused integer.
  • open() requires one access mode (O_RDONLY, O_WRONLY, or O_RDWR, tested via O_ACCMODE) combined with creation and status flags (O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_CLOEXEC).
  • Whenever O_CREAT or O_TMPFILE is present, pass the third mode_t argument (0644 or S_I* macros); the kernel applies effective_mode = mode & ~umask, and custom bitmasks must use unsigned shifts (1U << bit).
  • Close descriptors in reverse acquisition order on error paths so long-running daemons never exhaust RLIMIT_NOFILE (EMFILE).
GL-C01 · Linux Systems I/O & Buffering in C118/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Summary

  • Next, with open descriptors in hand, we will implement binary-safe write_all() and read_full() loops ac…
GL-C01 · Linux Systems I/O & Buffering in C119/515

GL-C01 · 2.1 (m02-l01)

>_ Kernel Systems Academy

Key takeaways

  • Whenever O_CREAT or O_TMPFILE is present, pass the third mode_t argument (0644 or S_I* macros); the kernel applies effective_mode = mode & ~umask, and custom bitmasks must use unsigned shifts (1U << bit).
  • Close descriptors in reverse acquisition order on error paths so long-running daemons never exhaust RLIMIT_NOFILE (EMFILE).
  • Next, with open descriptors in hand, we will implement binary-safe write_all() and read_full() loops across all four ssize_t return regimes, MAX_RW_COUNT, and Linux close() error semantics.
GL-C01 · Linux Systems I/O & Buffering in C120/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Byte I/O with write, read & close

free preview25 min

What you'll learn

  • Classify all four ssize_t return regimes of read() and write() (full, short count, MAX_RW_COUNT, 0 EOF, -1).
  • Implement binary-safe write_all() and read_full() retry loops over uint8_t * buffers without NUL assumptions.
  • Audit close(fd) returns for deferred writeback EIO faults without ever retrying close() after EINTR on Linux.
GL-C01 · Linux Systems I/O & Buffering in C121/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Why Single-Shot read() / write() & Retried close() Corrupt Data

  • Consider three bugs pulled straight from real incident postmortems.
GL-C01 · Linux Systems I/O & Buffering in C122/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Why Single-Shot read() / write() & Retried close() Corrupt Data

  • Single-shot transfers fail because POSIX read() and write() are byte-stream primitives permitted to tra…
GL-C01 · Linux Systems I/O & Buffering in C123/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Mental model

note: Think of unloading a 64-crate freight container with a forklift whose pallet load varies per trip. After each trip you count the crates actually moved, advance your manifest tally, and loop until zero crates remain—or stop cleanly when the container is empty.

Where it stops working: Unlike physical crates, a signal arriving mid-transfer before any byte moves causes read() or write() to return -1 with EINTR rather than 0.

GL-C01 · Linux Systems I/O & Buffering in C124/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Short Counts, MAX_RW_COUNT & Linux close()

definition: Short Count (0 < n < count) & MAX_RW_COUNT (0x7ffff000): In POSIX read() and write(), any positive ssize_t return value strictly smaller than count is a legal partial transfer, not an error. Inside the Linux kernel (include/linux/fs.h), MAX_RW_COUNT (INT_MAX & PAGE_MASK = 0x7ffff000 = 2,147,479,552 bytes) caps every individual VFS transfer one 4 KiB page below 2 GiB so internal 32-bit page-offset calculations never overflow. Linux close() Contract (close(2)): The kernel removes fd from files_struct unconditionally upon syscall entry; deferred writeback failures return -1 (EIO), and retrying close(fd) is strictly forbidden.

GL-C01 · Linux Systems I/O & Buffering in C125/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

One Layer Down: All Four ssize_t Regimes & Pointer-Advance Math

  • Every call to ssize_t read(int fd, void *buf, size_t count) or `ssize_t write(int fd, const void *buf, si…
GL-C01 · Linux Systems I/O & Buffering in C126/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

One Layer Down: All Four ssize_t Regimes & Pointer-Advance Math

fig_m02_l02_arch.svg

Figure 2.2: All four ssize_t return regimes, MAX_RW_COUNT (0x7ffff000) chunking, and single-shot Linux close(fd) semantics.

GL-C01 · Linux Systems I/O & Buffering in C127/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

One Layer Down: All Four ssize_t Regimes & Pointer-Advance Math

Cast void * to uint8_t * so byte-exact pointer advancement (p + done) obeys strict ISO C11.

Robust POSIX byte I/O wraps every read() and write() in a uint8_t * retry loop and checks close(fd) exactly once without retrying.

GL-C01 · Linux Systems I/O & Buffering in C128/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Prototypes, Raw Non-NUL Buffers & close(2) Reference

  • Include <unistd.h>, <errno.h>, and <stdint.h> under #define _POSIX_C_SOURCE 200809L.
GL-C01 · Linux Systems I/O & Buffering in C129/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

read

read(2) at a glance — GL-C01
read(2)                     GL-C01 Quick Reference                     read(2) NAME       read, write, close - transfer raw bytes across an open file descriptor SYNOPSIS       #include <unistd.h>       ssize_t read(int fd, void *buf, size_t count);       ssize_t write(int fd, const void *buf, size_t count);       int close(int fd); STANDARDS       POSIX.1-2008; Linux caps single calls to MAX_RW_COUNT (0x7ffff000). RETURN VALUE       read() and write() return bytes transferred (>= 0; 0 on read means       EOF), or -1 with errno set. close() returns 0 on success or -1 on       error. ERRORS       EAGAIN Non-blocking descriptor (O_NONBLOCK) cannot transfer       immediately. Kernel Systems Academy                     m02-l02                     read(2) GL-C01 quick reference · full manual page: man 2 read 
GL-C01 · Linux Systems I/O & Buffering in C130/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Implementing Pipe-Tested write_all() and read_full() Loops

  • Save short_io_loop.c below.
GL-C01 · Linux Systems I/O & Buffering in C131/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

short_io_loop.c

learner@ksa: ~/gl-c01/m02-l02
learner@ksa:~/gl-c01/m02-l02$ bat short_io_loop.c File: short_io_loop.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <unistd.h>        static int write_all(int fd, const void *buf, size_t count) {        const uint8_t *p = (const uint8_t *)buf;        size_t left = count;        while (left > 0U) {
GL-C01 · Linux Systems I/O & Buffering in C132/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Verifying Pipe Short Reads, Binary Reassembly & strace

  • Compile short_io_loop.c, verify the real 7-byte short pipe read (pipe_short=7), byte-exact 64-byte…
GL-C01 · Linux Systems I/O & Buffering in C133/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Verifying Pipe Short Reads, Binary Reassembly & strace

learner@ksa: ~/gl-c01/m02-l02
learner@ksa:~/gl-c01/m02-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror short_io_loop.c -o short_io_looplearner@ksa:~/gl-c01/m02-l02./short_io_looplearner@ksa:~/gl-c01/m02-l02strace -e trace=write ./short_io_loop 2>&1 >/dev/null | grep -c '^write('first_window=20 rest_window=44 total_match=1eof_read=0 label=HDR0 pipe_short=7 calls_ge_1=16learner@ksa:~/gl-c01/m02-l02
GL-C01 · Linux Systems I/O & Buffering in C134/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Verifying Pipe Short Reads, Binary Reassembly & strace

  • Under strace, observe the two pipe writes (7 and 13 bytes), the three file writes (17, 19, and `2…
GL-C01 · Linux Systems I/O & Buffering in C135/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Verifying Pipe Short Reads, Binary Reassembly & strace

strace — learner@ksa: ~/gl-c01/m02-l02
learner@ksa:~/gl-c01/m02-l02strace -e trace=openat,write,read,close ./short_io_loop
GL-C01 · Linux Systems I/O & Buffering in C136/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Why write_all() and read_full() Anchor Every Storage Protocol

  • Look at strace_m02_l02: when pfd[1] held only 7 bytes, read(pfd[0], prx, 20) legally returned 7 (…
GL-C01 · Linux Systems I/O & Buffering in C137/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Guided Practice: Diagnosing a Torn-Header Framing Bug

  • A student writes a length-prefixed packet reader `uint32_t len; if (read(fd, &len, 4) <= 0) return -1; read…
GL-C01 · Linux Systems I/O & Buffering in C138/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Guided Practice: Diagnosing a Torn-Header Framing Bug

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C139/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Independent Practice: CLOCK_MONOTONIC Chunk-Size Throughput Sweep

  • Write a C11 benchmark chunk_sweep.c (-std=c11 -O2 -Wall -Wextra -Werror) that writes and reads back a `…
GL-C01 · Linux Systems I/O & Buffering in C140/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: Calling char buf[64]; ssize_t n = read(fd, buf, 64); printf("%s\n", buf); prints valid configuration text followed by binary stack garbage or crashes with SIGSEGV. Root Cause: read() copies raw bytes and never appends a '\0' terminator; when n == 64 (or n < 64 over dirty stack bytes), %s scans past valid data until hitting a chance zero byte. Fix: Read at most sizeof(buf) - 1 bytes and assign buf[n] = '\0', or use printf("%.*s\n", (int)n, buf).

GL-C01 · Linux Systems I/O & Buffering in C141/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: Wrapping close(fd) in while (close(fd) == -1 && errno == EINTR) {} inside a multithreaded daemon randomly closes another thread's newly opened file or client socket! Root Cause: On the Linux kernel, close(fd) releases slot fd from files_struct before flushing driver state; if a sibling thread immediately allocates that lowest unused fd, retrying close(fd) closes the sibling's handle! Fix: Check if (close(fd) == -1) once to log deferred EIO, and never retry close(fd) on Linux.

GL-C01 · Linux Systems I/O & Buffering in C142/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) What happens when size_t n = read(fd, buf, 256); executes on an invalid descriptor (EBADF) inside a while (total < 256) loop?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C143/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

When read(fd, buf, 4096) returns 0 on a regular file or open pipe, what state did the caller encounter?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C144/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

If the Linux kernel automatically closes all open descriptors when a process exits, why must long-running C services explicitly call and check close(fd)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C145/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Quick check

On 64-bit Linux, a backup engine allocates a 3 GiB RAM buffer and calls ssize_t n = read(fd, buf, 3ULL << 30); once on a local 4 GiB ext4 disk file with zero signals pending. What does read() return?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C146/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Summary

  • write() and read() return signed ssize_t across four regimes: full count, positive short count (0 < n < count, including the Linux MAX_RW_COUNT 0x7ffff000 cap), 0 (clean EOF on read()), and -1 (EINTR retry vs fatal errno).
  • Wrap binary transfers in write_all() and read_full() loops that cast void * to uint8_t * and advance (p + done, count - done).
  • Never pass raw read() buffers to NUL-terminated string routines without reserving sizeof(buf) - 1 and writing '\0' explicitly.
  • Always call close(fd), check close(fd) == -1 for deferred EIO faults, and never retry close(fd) on the Linux kernel.
GL-C01 · Linux Systems I/O & Buffering in C147/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Summary

  • Next, we move beyond sequential byte streams to random-access cursor positioning with 64-bit lseek(), spa…
GL-C01 · Linux Systems I/O & Buffering in C148/515

GL-C01 · 2.2 (m02-l02)

>_ Kernel Systems Academy

Key takeaways

  • Never pass raw read() buffers to NUL-terminated string routines without reserving sizeof(buf) - 1 and writing '\0' explicitly.
  • Always call close(fd), check close(fd) == -1 for deferred EIO faults, and never retry close(fd) on the Linux kernel.
  • Next, we move beyond sequential byte streams to random-access cursor positioning with 64-bit lseek(), sparse-extent queries (SEEK_DATA/SEEK_HOLE), and pre-validated byte slicing.
GL-C01 · Linux Systems I/O & Buffering in C149/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

File Offsets & lseek Slicing

free preview25 minlab lab_m02_framed_copy

What you'll learn

  • Reposition struct file.f_pos via 64-bit lseek() (SEEK_SET, SEEK_CUR, SEEK_END, SEEK_DATA, SEEK_HOLE).
  • Diagnose signed off_t overflow hazards, negative-offset EINVAL errors, and ESPIPE rejections on pipes and sockets.
  • Construct all five canonical POSIX open() and lseek() byte-slicing patterns after pre-validating source bounds.
GL-C01 · Linux Systems I/O & Buffering in C150/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Why Shared f_pos Cursors & Eager O_TRUNC Opens Destroy Files

  • Two subtle failures appear whenever engineers graduate from sequential read()/write() streams to random…
GL-C01 · Linux Systems I/O & Buffering in C151/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Why Shared f_pos Cursors & Eager O_TRUNC Opens Destroy Files

  • Random-access I/O requires three engineering habits: explicit cursor positioning via 64-bit lseek(), over…
GL-C01 · Linux Systems I/O & Buffering in C152/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Mental model

note: Think of a magnetic tape deck equipped with a digital byte counter. Every play or record pass advances the counter automatically by the bytes transferred, while fast-forward or rewind jumps the tape head relative to zero, the current counter, or the tape end.

Where it stops working: Unlike physical tape, lseek() updates only an in-memory integer offset inside the Linux kernel without spinning disks or transferring a single byte.

GL-C01 · Linux Systems I/O & Buffering in C153/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Shared File Offset (f_pos), lseek() & Extent Seeks

definition: File Offset (f_pos) & lseek(fd, offset, whence): Named from "long seek" in Seventh Edition Unix (when file offsets widened from 16-bit int to 32-bit long, and later to signed 64-bit off_t under _FILE_OFFSET_BITS=64), lseek() updates the in-memory f_pos coordinate inside the kernel's open file description relative to SEEK_SET (0), SEEK_CUR (f_pos), or SEEK_END (i_size). Linux 3.1+ (standardized in POSIX.1-2024) adds SEEK_DATA and SEEK_HOLE to jump directly across allocated extents and sparse holes in O(extents) metadata time.

GL-C01 · Linux Systems I/O & Buffering in C154/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns

  • Inside fs/read_write.c (ksys_lseek), the Linux kernel acquires file->f_pos_lock (a per-struct file…
GL-C01 · Linux Systems I/O & Buffering in C155/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns

  • Because off_t is signed ([-2^63, 2^63 - 1] under _FILE_OFFSET_BITS=64 so negative SEEK_CUR delt…
GL-C01 · Linux Systems I/O & Buffering in C156/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns

fig_m02_l03_arch.svg

Figure 2.3: Positioning struct file.f_pos with lseek(), guarding 64-bit off_t subtraction bounds, and pre-validating sources before O_TRUNC opens.

GL-C01 · Linux Systems I/O & Buffering in C157/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

One Layer Down: f_pos_lock, Signed off_t Algebra & Five Canonical Patterns

Probe source size with lseek(sfd, 0, SEEK_END) first so pipes/sockets fail fast with ESPIPE before touching dst.

Validate source seekability and subtraction bounds via lseek() before opening any destination pathname with O_CREAT | O_TRUNC.

GL-C01 · Linux Systems I/O & Buffering in C158/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

64-Bit lseek(2) Reference & Cross-Architecture ILP32 Rules

  • Always define #define _FILE_OFFSET_BITS 64 (plus #define _GNU_SOURCE when calling SEEK_DATA / `SEEK_H…
GL-C01 · Linux Systems I/O & Buffering in C159/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

lseek

lseek(2) at a glance — GL-C01
lseek(2)                    GL-C01 Quick Reference                    lseek(2) NAME       lseek - reposition read/write file offset inside struct file SYNOPSIS       #define _FILE_OFFSET_BITS 64       #include <unistd.h>       off_t lseek(int fd, off_t offset, int whence); STANDARDS       POSIX.1-2008; SEEK_DATA and SEEK_HOLE require _GNU_SOURCE (or       POSIX.1-2024). RETURN VALUE       Returns resulting byte offset from start of file, or (off_t)-1 on       error. ERRORS       EBADF  fd is not an open file descriptor.        EINVAL whence is invalid, or resulting file offset would be negative.        ENXIO  SEEK_DATA or SEEK_HOLE offset is at or beyond end-of-file. Kernel Systems Academy                    m02-l03                     lseek(2) GL-C01 quick reference · full manual page: man 2 lseek 
GL-C01 · Linux Systems I/O & Buffering in C160/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Implementing All Five Canonical Patterns & Extent Seeks in C11

  • Save offset_patterns.c below.
GL-C01 · Linux Systems I/O & Buffering in C161/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

offset_patterns.c

learner@ksa: ~/gl-c01/m02-l03
learner@ksa:~/gl-c01/m02-l03$ bat offset_patterns.c File: offset_patterns.c    #define _GNU_SOURCE    #define _FILE_OFFSET_BITS 64    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <sys/types.h>    #include <unistd.h>        static int safe_add_off(off_t cur, off_t delta, off_t *out) {        if (delta > 0 && cur > (off_t)INT64_MAX - delta) {
GL-C01 · Linux Systems I/O & Buffering in C162/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Tracing lseek Calls and Completing Lab 2

  • Check the exact boundary indices before executing: starting at byte 500, [500..1023] spans 524 zero b…
GL-C01 · Linux Systems I/O & Buffering in C163/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Tracing lseek Calls and Completing Lab 2

learner@ksa: ~/gl-c01/m02-l03
learner@ksa:~/gl-c01/m02-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror offset_patterns.c -o offset_patternslearner@ksa:~/gl-c01/m02-l03printf 'stream' | ./offset_patternslearner@ksa:~/gl-c01/m02-l03printf 'stream' | strace -e trace=lseek ./offset_patterns 2>&1 | grep -c 'SEEK_'learner@ksa:~/gl-c01/m02-l03rm -f offset_patternsp1_enoent=1 p3_eexist=1 src_size=2048 dst_size=1024cur_after=1524 boundary=0x00,0xff ovf=1 ext=1 err=1,18learner@ksa:~/gl-c01/m02-l03
GL-C01 · Linux Systems I/O & Buffering in C164/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Lab: lab_m02_framed_copy

  • 1.

Verify: ./check.sh exits 0.

GL-C01 · Linux Systems I/O & Buffering in C165/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Zero-Disk f_pos Updates Bridge to Kernel Open-File Tables

  • Every lseek() in offset_patterns updated file->f_pos in kernel RAM with zero block transfers, extract…
GL-C01 · Linux Systems I/O & Buffering in C166/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Guided Practice: Cursor-Preserving Header Peek Helper

  • Write a helper int peek_magic_at_zero(int fd, uint32_t *magic_out) that reads the 4-byte header at byte `…
GL-C01 · Linux Systems I/O & Buffering in C167/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Guided Practice: Cursor-Preserving Header Peek Helper

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C168/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Independent Practice: Reverse-Chunk Binary Trailer Scanner

  • Write a C11 utility tail_magic_scan.c (_FILE_OFFSET_BITS=64, -Wall -Wextra -Werror) that locates the…
GL-C01 · Linux Systems I/O & Buffering in C169/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Overwriting a 7,000-byte configuration file with a new 5,200-byte payload via open(dst, O_WRONLY | O_CREAT, 0644) leaves 1,800 bytes of stale trailing text at [5200..6999]! Root Cause: Omitting O_TRUNC preserves existing i_size and trailing blocks past the newly written prefix. Fix: Pass O_TRUNC on full-file overwrites (or write a staged temporary file and rename() atomically).

GL-C01 · Linux Systems I/O & Buffering in C170/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Cross-compiling a partition-slicing tool for 32-bit ARMv7 (Cortex-A7) works on 500 MiB test files, then fails in the field with EOVERFLOW on a 3 GiB rootfs image. Root Cause: Without #define _FILE_OFFSET_BITS 64 before system headers, 32-bit ILP32 off_t is a signed 32-bit long capped at 2,147,483,647 bytes. Fix: Define _FILE_OFFSET_BITS 64 at line 1 of every C11 I/O source file (or in CFLAGS).

GL-C01 · Linux Systems I/O & Buffering in C171/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

Which lseek() invocation lets a diagnostic helper retrieve the active byte offset of a seekable descriptor fd without changing its position?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C172/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) Why must copy_slice() validate src_fd with lseek(src_fd, 0, SEEK_END) before calling open(dst_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C173/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

An application opens a brand-new file with O_RDWR | O_CREAT | O_TRUNC, writes 512 bytes via write_all(), and immediately calls read_full(fd, buf, 512). What does read_full() return?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C174/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Quick check

A virtual-machine archiver needs to copy only allocated data extents from a 64 GiB sparse image (63 GiB unallocated holes) without polluting the kernel page cache. Which Linux lseek() idiom achieves O(extents) traversal?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C175/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Summary

  • Sequential read() and write() calls automatically advance the descriptor's shared byte offset f_pos by the transferred count.
  • lseek(fd, offset, whence) repositions f_pos relative to SEEK_SET, SEEK_CUR (lseek(fd, 0, SEEK_CUR) queries position), SEEK_END, or sparse extents (SEEK_DATA, SEEK_HOLE).
  • Guard signed 64-bit off_t bounds via subtraction (req_len <= (size_t)(src_sz - req_off)) under _FILE_OFFSET_BITS 64, and handle (off_t)-1 errors (EINVAL on negative target offsets, ESPIPE on pipes/sockets).
  • Combine ENOENT probes, O_CREAT | O_EXCL atomic creation, O_TRUNC overwrites, and pre-validated SEEK_END bounds checks to build side-effect-safe binary slicing tools.
GL-C01 · Linux Systems I/O & Buffering in C176/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Summary

  • With core unbuffered POSIX file operations complete, Module 3 peers inside the Linux kernel to map static o…
GL-C01 · Linux Systems I/O & Buffering in C177/515

GL-C01 · 2.3 (m02-l03)

>_ Kernel Systems Academy

Key takeaways

  • Guard signed 64-bit off_t bounds via subtraction (req_len <= (size_t)(src_sz - req_off)) under _FILE_OFFSET_BITS 64, and handle (off_t)-1 errors (EINVAL on negative target offsets, ESPIPE on pipes/sockets).
  • Combine ENOENT probes, O_CREAT | O_EXCL atomic creation, O_TRUNC overwrites, and pre-validated SEEK_END bounds checks to build side-effect-safe binary slicing tools.
  • With core unbuffered POSIX file operations complete, Module 3 peers inside the Linux kernel to map static on-disk inodes, the three-tier dynamic VFS open-file hierarchy, thread-local errno unwinding, and sparse extent holes.
GL-C01 · Linux Systems I/O & Buffering in C178/515

m03/

>_ Kernel Systems Academy

Kernel Open-File Internals, Errors & Sparse Files

Trace static on-disk directory entries and inodes into the dynamic 3-tier Linux kernel VFS open-file hierarchy, preserve thread-local errno across exit() vs _exit() termination paths, and engineer sparse hole files with O_TRUNC and O_APPEND.

  1. 3.1 Disk Inodes & Kernel VFS Tables
  2. 3.2 Thread-Local errno & Exit Paths
  3. 3.3 Sparse Holes, O_TRUNC & O_APPEND

lab → Sparse Partition Image Builder & Hole Inspector

GL-C01 · Linux Systems I/O & Buffering in C179/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Disk Inodes & Kernel VFS Tables

free preview25 min

What you'll learn

  • Distinguish static disk structures (superblock, inode table, dentries, 4 KiB blocks) from dynamic VFS RAM tables.
  • Trace files_struct -> struct file (f_pos, f_op) -> struct inode and type-safe CONTAINER_OF / offsetof math.
  • Inspect hard-link st_ino/st_nlink sharing via stat() and live f_pos/O_CLOEXEC flags in /proc/self/fdinfo.
GL-C01 · Linux Systems I/O & Buffering in C180/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames

  • Every production systems engineer eventually receives the midnight alert: /var/log is 99% full, an oper…
GL-C01 · Linux Systems I/O & Buffering in C181/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames

  • Mental models that picture a "file" as a named blob attached directly to an integer fd break down complet…
GL-C01 · Linux Systems I/O & Buffering in C182/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Mental model

note: Think of a library card catalog versus an active reading-room checkout slip. Multiple catalog cards in different drawers can reference the exact same numbered shelf volume, while each reader at a table holds a personal bookmark slip tracking their current page in that volume.

Where it stops working: Unlike paper catalog cards, the Linux kernel caches active 4 KiB book pages inside shared RAM (the page cache) rather than fetching from disk on every read or write.

GL-C01 · Linux Systems I/O & Buffering in C183/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Directory Entry (dentry), Inode, Three-Tier VFS & CONTAINER_OF

definition: Index Node (inode) vs Directory Entry (dentry): Named by Dennis Ritchie for "index node", an on-disk inode stores numeric ownership (st_uid, st_gid), st_mode, st_size, st_blocks, hard-link count (st_nlink), and data-block extents—never the filename. Parent directory entries (dentries) map human strings ("sensor.log") to st_ino numbers. Three-Tier VFS Hierarchy: open() links per-process files_struct (fd, FD_CLOEXEC) -> system-wide struct file (f_pos, f_flags, f_count, f_op) -> shared VFS struct inode + 4 KiB RAM Page Cache, while CONTAINER_OF(ptr, type, member) recovers enclosing driver structs from embedded VFS anchors via offsetof subtraction.

GL-C01 · Linux Systems I/O & Buffering in C184/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Why rm Can Free Zero Disk Bytes & Inodes Never Store Filenames

ast_m03_l01_inode_table.svg

Figure 3.1a: Static ext4 disk layout — directory entries map filenames to inode numbers in the Inode Table, which index 4 KiB data blocks.

GL-C01 · Linux Systems I/O & Buffering in C185/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math

  • On non-volatile storage, 512-byte hardware sectors are grouped into 4 KiB (4,096-byte) filesystem blo…
GL-C01 · Linux Systems I/O & Buffering in C186/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math

  • How does pure ISO C inside the Linux kernel dispatch a single read(fd, buf, len) syscall across ext4 ex…
GL-C01 · Linux Systems I/O & Buffering in C187/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math

fig_m03_l01_arch.svg

Figure 3.1b: Dynamic Linux kernel VFS pointer chain (task_struct -> fdtable -> struct file -> inode -> address_space), orphan block survival, and CONTAINER_OF recovery.

GL-C01 · Linux Systems I/O & Buffering in C188/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

One Layer Down: Block Geometry, Reclamation Condition & CONTAINER_OF Math

Each process PCB (task_struct) owns a private files_struct slot array storing FD_CLOEXEC and a struct file pointer.

Filenames map to inode numbers on disk, while open descriptors index through private FD slots into struct file cursors and one shared VFS inode page cache.

GL-C01 · Linux Systems I/O & Buffering in C189/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Observing Live VFS State with stat(), link() & /proc/self/fdinfo

  • Include <sys/stat.h>, <fcntl.h>, <stddef.h>, and <unistd.h> under #define _POSIX_C_SOURCE 200809L.
GL-C01 · Linux Systems I/O & Buffering in C190/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Probing Hard Links, Orphaned Open Inodes, CONTAINER_OF & fdinfo

  • Save vfs_fdinfo_probe.c below.
GL-C01 · Linux Systems I/O & Buffering in C191/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

vfs_fdinfo_probe.c

learner@ksa: ~/gl-c01/m03-l01
learner@ksa:~/gl-c01/m03-l01$ bat vfs_fdinfo_probe.c File: vfs_fdinfo_probe.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stddef.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <unistd.h>        #define CONTAINER_OF(ptr, type, member) \        ((type *)((char *)(1 ? (ptr) : &((type *)0)->member) - \                  offsetof(type, member)))
GL-C01 · Linux Systems I/O & Buffering in C192/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Verifying Shared st_ino, Orphan Inode Survival & fdinfo

  • Compile and execute vfs_fdinfo_probe: confirm path_a and path_b share one st_ino (hard_links=2),…
GL-C01 · Linux Systems I/O & Buffering in C193/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Verifying Shared st_ino, Orphan Inode Survival & fdinfo

learner@ksa: ~/gl-c01/m03-l01
learner@ksa:~/gl-c01/m03-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror vfs_fdinfo_probe.c -o vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01./vfs_fdinfo_probelearner@ksa:~/gl-c01/m03-l01strace -e trace=link,linkat ./vfs_fdinfo_probe 2>&1 | grep -c 'ksa_vfs_b.dat'learner@ksa:~/gl-c01/m03-l01rm -f vfs_fdinfo_probesame_inode=1 hard_links=2 st_size=128 orphan_alive=1fdinfo_pos=128 cloexec_in_flags=1 intrusive_ok=11learner@ksa:~/gl-c01/m03-l01
GL-C01 · Linux Systems I/O & Buffering in C194/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Why Page-Cache & Reference-Counted Inodes Outlive Directory Names

  • Notice how orphan_alive=1 demystified the 10 GiB unlinked-log incident in twenty lines of C!
GL-C01 · Linux Systems I/O & Buffering in C195/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Guided Practice: Tracing CONTAINER_OF Byte Arithmetic by Hand

  • Given struct rx_ring { uint64_t drops; uint32_t mask; struct vfs_hook hook; }; on 64-bit Linux where `&r.…
GL-C01 · Linux Systems I/O & Buffering in C196/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Guided Practice: Tracing CONTAINER_OF Byte Arithmetic by Hand

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C197/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Independent Practice: Live Process Open-File & Orphan Inspector

  • Write a C11 tool self_fd_audit.c that opens two regular files (unlinking one while keeping its descriptor…
GL-C01 · Linux Systems I/O & Buffering in C198/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: Removing a runaway /var/log/app.log file with rm clears the directory listing, yet df -h shows 0 freed gigabytes and new writes fail with ENOSPC. Root Cause: The running process still holds an open struct file (f_count > 0) referencing the unlinked inode (st_nlink == 0), blocking block reclamation until close(). Fix: Signal the service (SIGHUP / SIGUSR1) to close and reopen its log descriptor, or truncate the active file in place (truncate -s 0 / O_TRUNC).

GL-C01 · Linux Systems I/O & Buffering in C199/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: Decommissioning an embedded flash partition after unlink() or a quick mkfs allows forensic sector reads to recover plaintext keys. Root Cause: Quick-formatting resets only the superblock and inode/block bitmaps, and unlink() clears directory entries and inode metadata without overwriting physical 4 KiB data blocks. Fix: Overwrite sensitive payloads explicitly (fdatasync before unlink) or issue block-device secure erase (BLKSECDISCARD).

GL-C01 · Linux Systems I/O & Buffering in C200/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

Where is a regular file's human-readable filename stored inside a POSIX filesystem such as ext4?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C201/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) Which kernel structure stores the active byte offset f_pos returned by lseek(fd, 0, SEEK_CUR)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C202/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

When two independent processes open /etc/hosts with O_RDONLY simultaneously, how many copies of /etc/hosts's 4 KiB data pages does the Linux kernel maintain in RAM?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C203/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Quick check

How does the Linux VFS implement zero-overhead polymorphism and generic intrusive list manipulation in ISO C across ext4, pipefs, procfs, and /dev drivers?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C204/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Summary

  • Block storage groups 512-byte sectors into 4 KiB blocks organized into boot block, superblock, inode table (metadata + extents, never filenames), and directory/data blocks.
  • Directory entries map filenames to st_ino numbers (ls -i, stat()), allowing hard links (link()) to share one underlying inode (st_nlink >= 2).
  • Calling open() links three dynamic kernel RAM tiers: per-process files_struct (fd, FD_CLOEXEC) -> system-wide struct file (f_flags, f_pos, f_count, f_op) -> shared VFS struct inode + page cache.
  • VFS dispatches generic syscalls through struct file_operations vtables while subsystems recover enclosing types intrusively via offsetof (CONTAINER_OF) and unlink list nodes via struct node **pp.
GL-C01 · Linux Systems I/O & Buffering in C205/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Summary

  • Next, we trace how VFS failures propagate back to user space via thread-local errno, how multi-resource f…
GL-C01 · Linux Systems I/O & Buffering in C206/515

GL-C01 · 3.1 (m03-l01)

>_ Kernel Systems Academy

Key takeaways

  • VFS dispatches generic syscalls through struct file_operations vtables while subsystems recover enclosing types intrusively via offsetof (CONTAINER_OF) and unlink list nodes via struct node **pp.
  • /proc/self/fdinfo/<fd> exposes live kernel pos: and octal flags:, and physical blocks are reclaimed only when both st_nlink == 0 and f_count == 0.
  • Next, we trace how VFS failures propagate back to user space via thread-local errno, how multi-resource functions unwind cleanly in reverse (LIFO) order, and why exit() and _exit() diverge on buffered output.
GL-C01 · Linux Systems I/O & Buffering in C207/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Thread-Local errno & Exit Paths

free preview20 min

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.
GL-C01 · Linux Systems I/O & Buffering in C208/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Why Intervening Calls Clobber errno & _exit() Drops Output

  • Two bugs turn routine error-handling code into hours of misdirection.
GL-C01 · Linux Systems I/O & Buffering in C209/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Why Intervening Calls Clobber errno & _exit() Drops Output

  • Reliable error handling and termination in systems C rest on three strict mechanisms: preserving thread-loc…
GL-C01 · Linux Systems I/O & Buffering in C210/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Mental model

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.

GL-C01 · Linux Systems I/O & Buffering in C211/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Thread-Local errno, strerror_r(), LIFO goto & _exit()

definition: 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().

GL-C01 · Linux Systems I/O & Buffering in C212/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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…
GL-C01 · Linux Systems I/O & Buffering in C213/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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

  • In functions acquiring k resources sequentially (R_1 = open, R_2 = mmap, R_3 = malloc), naive neste…
GL-C01 · Linux Systems I/O & Buffering in C214/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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

fig_m03_l02_arch.svg

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

GL-C01 · Linux Systems I/O & Buffering in C215/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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

Initialize int rc = -1 and NULL/-1 sentinels up front so early goto jumps never mask errors or free garbage.

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

GL-C01 · Linux Systems I/O & Buffering in C216/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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

  • Watch a subtle header portability detail on Linux: under #define _POSIX_C_SOURCE 200809L without `_GN…
GL-C01 · Linux Systems I/O & Buffering in C217/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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

  • Save errno_exit_lab.c below.
GL-C01 · Linux Systems I/O & Buffering in C218/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

errno_exit_lab.c

learner@ksa: ~/gl-c01/m03-l02
learner@ksa:~/gl-c01/m03-l02$ bat 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);
GL-C01 · Linux Systems I/O & Buffering in C219/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Comparing Flushed exit() vs Dropped _exit() Output

  • Compile errno_exit_lab, redirect emit_exit and emit_uexit into /tmp files, verify `exit_flushed_byt…
GL-C01 · Linux Systems I/O & Buffering in C220/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Comparing Flushed exit() vs Dropped _exit() Output

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_lablearner@ksa:~/gl-c01/m03-l02strace -e trace=exit_group ./errno_exit_lab emit_uexit 2>&1 >/dev/null | grep -c 'exit_group(0)'learner@ksa:~/gl-c01/m03-l02rm -f 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=101learner@ksa:~/gl-c01/m03-l02
GL-C01 · Linux Systems I/O & Buffering in C221/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Why Cleanup Ordering & User-Space Teardown Govern Reliability

  • Both emit_exit and emit_uexit ended at kernel exit_group(0) (`$?
GL-C01 · Linux Systems I/O & Buffering in C222/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Note

note: 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!

GL-C01 · Linux Systems I/O & Buffering in C223/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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 dire…
GL-C01 · Linux Systems I/O & Buffering in C224/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C225/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

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…
GL-C01 · Linux Systems I/O & Buffering in C226/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Warning

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().

GL-C01 · Linux Systems I/O & Buffering in C227/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Warning

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.

GL-C01 · Linux Systems I/O & Buffering in C228/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

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

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C229/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

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

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C230/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C231/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Quick check

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?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C232/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Summary

  • 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().
GL-C01 · Linux Systems I/O & Buffering in C233/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Summary

  • Next, we return to on-disk extent allocation to engineer sparse hole files, measure st_size versus `st_bl…
GL-C01 · Linux Systems I/O & Buffering in C234/515

GL-C01 · 3.2 (m03-l02)

>_ Kernel Systems Academy

Key takeaways

  • 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.
GL-C01 · Linux Systems I/O & Buffering in C235/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Sparse Holes, O_TRUNC & O_APPEND

free preview20 minlab lab_m03_sparse_image

What you'll learn

  • Construct sparse hole files by seeking past EOF with lseek() and verify VFS 0x00 synthesis across unallocated extents.
  • Measure logical st_size vs allocated 512-byte sectors (st_blocks * 512) via fstat() and reclaim extents via O_TRUNC.
  • Verify O_RDWR | O_APPEND cursor asymmetry proving lseek() governs read() while write() jumps f_pos to EOF.
GL-C01 · Linux Systems I/O & Buffering in C236/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Why Literal Zero-Fills Exhaust Flash & O_APPEND Ignores lseek() on Writes

  • Imagine two storage bugs that pass casual functional checks yet fail dramatically on embedded targets.
GL-C01 · Linux Systems I/O & Buffering in C237/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Why Literal Zero-Fills Exhaust Flash & O_APPEND Ignores lseek() on Writes

  • Both defects vanish once you understand how the Linux kernel decouples logical file length (st_size)…
GL-C01 · Linux Systems I/O & Buffering in C238/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Mental model

note: Think of a numbered loose-leaf binder versus a bound ledger stamped APPEND-ONLY. In the binder you can insert page 1,000 without buying paper for pages 2 through 999, whereas on the append-only ledger you may flip back to read page 1 anytime, yet every pen stroke is forced onto the bottom line.

Where it stops working: Unlike an empty gap in a ring binder, reading across an unallocated Linux sparse hole returns clean 0x00 bytes synthesized by VFS rather than an error.

GL-C01 · Linux Systems I/O & Buffering in C239/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Sparse Extent Holes, POSIX 512-Byte st_blocks & O_APPEND Asymmetry

definition: Sparse Extent Hole: When lseek() positions f_pos past current EOF (i_size) and a subsequent write() commits data, POSIX filesystems (ext4, XFS, Btrfs, tmpfs) record an unallocated extent gap (hole) for [old_eof .. seek_offset), allocating physical blocks only for written pages while VFS synthesizes 0x00 bytes on read(). struct stat.st_blocks: Defined in POSIX.1 in fixed 512-byte sector units (historically Seventh Edition Unix disk sectors, never st_blksize!) so physical byte allocation always equals st_blocks * 512. O_APPEND Asymmetry: On an O_RDWR | O_APPEND description, lseek() governs read() normally, whereas every write() atomically resets f_pos = i_size under inode->i_rwsem.

GL-C01 · Linux Systems I/O & Buffering in C240/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking

  • Inside ext4 or XFS, an inode's extent tree maps logical block numbers (4 KiB units) to physical devic…
GL-C01 · Linux Systems I/O & Buffering in C241/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking

  • Meanwhile, inspect how O_TRUNC and O_APPEND act at different lifecycle moments inside VFS:
GL-C01 · Linux Systems I/O & Buffering in C242/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking

fig_m03_l03_arch.svg

Figure 3.3: Logical st_size versus physical st_blocks * 512 on a sparse hole file, O_TRUNC extent reclamation, and O_RDWR | O_APPEND write-cursor override.

GL-C01 · Linux Systems I/O & Buffering in C243/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking

Seeking past EOF via lseek(hfd, 65536, SEEK_SET) advances f_pos in RAM without writing physical zero blocks.

Sparse holes decouple logical st_size from physical st_blocks * 512 allocation, while O_APPEND forces writes—never reads—to current i_size.

GL-C01 · Linux Systems I/O & Buffering in C244/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

fstat(2) Inspection Contract & Sparse-Filesystem Notes

  • Include <sys/stat.h>, <sys/types.h>, <fcntl.h>, and <unistd.h> under #define _FILE_OFFSET_BITS 64…
GL-C01 · Linux Systems I/O & Buffering in C245/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Probing Sparse Holes, O_TRUNC Reclamation & O_RDWR | O_APPEND

  • Save hole_append_probe.c below.
GL-C01 · Linux Systems I/O & Buffering in C246/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

hole_append_probe.c

learner@ksa: ~/gl-c01/m03-l03
learner@ksa:~/gl-c01/m03-l03$ bat hole_append_probe.c File: hole_append_probe.c    #define _FILE_OFFSET_BITS 64    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <sys/types.h>    #include <unistd.h>        int main(void) {        const char *hpath = "/tmp/ksa_hole_demo.bin";
GL-C01 · Linux Systems I/O & Buffering in C247/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Verifying Sparse Sector Counts, O_APPEND Asymmetry & Lab 3

  • Compile and run hole_append_probe, confirm hole_logical=69632 with hole_phys_lt=1 and trunc_sz=0, v…
GL-C01 · Linux Systems I/O & Buffering in C248/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Verifying Sparse Sector Counts, O_APPEND Asymmetry & Lab 3

learner@ksa: ~/gl-c01/m03-l03
learner@ksa:~/gl-c01/m03-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror hole_append_probe.c -o hole_append_probelearner@ksa:~/gl-c01/m03-l03./hole_append_probelearner@ksa:~/gl-c01/m03-l03strace -e trace=openat ./hole_append_probe 2>&1 | grep -c 'O_APPEND'learner@ksa:~/gl-c01/m03-l03rm -f hole_append_probehole_logical=69632 hole_phys_lt=1 hole_zero=1 trunc_sz=0append_read0=0x11 byte0_kept=0x11 eof_byte4=0x551learner@ksa:~/gl-c01/m03-l03
GL-C01 · Linux Systems I/O & Buffering in C249/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Lab: lab_m03_sparse_image

  • 1.

Verify: ./check.sh exits 0.

GL-C01 · Linux Systems I/O & Buffering in C250/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Kernel-Locked O_APPEND Sets Up Module 4 File Sharing

  • Inside fs/read_write.c, O_APPEND works because the kernel acquires inode->i_rwsem, sets `kiocb.ki_pos…
GL-C01 · Linux Systems I/O & Buffering in C251/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Guided Practice: Sparse-Aware File Copier Loop

  • A naive cp implementation copies a sparse image by calling read() and write() unconditionally, inflat…
GL-C01 · Linux Systems I/O & Buffering in C252/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Guided Practice: Sparse-Aware File Copier Loop

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C253/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Independent Practice: Extent Map & Sparsity Ratio Reporter

  • Write a C11 CLI sparse_stat.c (#define _GNU_SOURCE, #define _FILE_OFFSET_BITS 64, `-Wall -Wextra -Wer…
GL-C01 · Linux Systems I/O & Buffering in C254/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: A storage engine opens its file with O_RDWR | O_APPEND, executes lseek(fd, 0, SEEK_SET) + write(fd, &hdr, 64) to update a superblock checksum in place, and discovers byte 0 never changed while st_size grew by 64 bytes! Root Cause: O_APPEND overrides f_pos to i_size on every write() regardless of prior lseek() calls. Fix: Open descriptors requiring in-place header overwrites without O_APPEND (or use stateless pwrite() on a non-append descriptor).

GL-C01 · Linux Systems I/O & Buffering in C255/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Multiplying st.st_blocks * st.st_blksize to compute physical disk consumption over-reports storage usage by 8x on standard 4 KiB ext4 filesystems! Root Cause: POSIX fixes st_blocks in 512-byte units regardless of st_blksize (4,096 or 65,536). Fix: Always compute physical bytes as (long long)st.st_blocks * 512LL.

GL-C01 · Linux Systems I/O & Buffering in C256/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

A program creates an empty file on ext4, calls lseek(fd, 1048576, SEEK_SET) (1 MiB), and writes 64 bytes. What do st.st_size and (long long)st.st_blocks * 512LL report via fstat()?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C257/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) An existing 4-byte file {0x10, 0x20, 0x30, 0x40} is opened with open(path, O_RDWR | O_APPEND | O_CLOEXEC). The caller runs lseek(fd, 1, SEEK_SET), read(fd, &r, 1), lseek(fd, 0, SEEK_SET), and write(fd, &w, 1) where w = 0x99. What byte does read() fetch, and at what offset does 0x99 land?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C258/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

(Review from previous module) What happens when an existing 8 KiB log file is opened via open(path, O_WRONLY | O_APPEND | O_TRUNC | O_CLOEXEC) and the process writes two 16-byte records?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C259/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Quick check

On an XFS partition formatted with a 64 KiB (65,536-byte) block size (st.st_blksize == 65536), fstat() on a small file reports st.st_blocks == 128. How many physical bytes are allocated on disk?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C260/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Summary

  • Seeking past EOF with lseek() and calling write() creates a sparse hole file: read() across unallocated holes returns VFS-synthesized 0x00 bytes without consuming physical disk blocks.
  • fstat() separates logical byte length st.st_size (ls -lh) from physical allocation (long long)st.st_blocks * 512LL (du -h, unconditionally counted in 512-byte POSIX units).
  • O_TRUNC (paired with O_WRONLY or O_RDWR) resets st_size to 0 and reclaims allocated extents during open().
  • O_APPEND leaves read() seekable via lseek(), yet forces every write() inside the Linux kernel to jump atomically to i_size regardless of prior lseek() calls.
GL-C01 · Linux Systems I/O & Buffering in C261/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Summary

  • With VFS tables, errno unwinding, and sparse extents in place, Module 4 tackles descriptor sharing (`dup2…
GL-C01 · Linux Systems I/O & Buffering in C262/515

GL-C01 · 3.3 (m03-l03)

>_ Kernel Systems Academy

Key takeaways

  • O_TRUNC (paired with O_WRONLY or O_RDWR) resets st_size to 0 and reclaims allocated extents during open().
  • O_APPEND leaves read() seekable via lseek(), yet forces every write() inside the Linux kernel to jump atomically to i_size regardless of prior lseek() calls.
  • With VFS tables, errno unwinding, and sparse extents in place, Module 4 tackles descriptor sharing (dup2/dup3), atomic O_EXCL & stateless pread/pwrite, and runtime fcntl/ioctl control.
GL-C01 · Linux Systems I/O & Buffering in C263/515

m04/

>_ Kernel Systems Academy

File Sharing, Atomic Operations & Descriptor Control

Control kernel open-file table sharing across dual opens and dup/dup2/dup3, eliminate TOCTOU and offset races with O_EXCL and stateless pread/pwrite, and manipulate live descriptors with fcntl, ioctl, and ftruncate.

  1. 4.1 Shared File Tables & dup Redirection
  2. 4.2 Atomic Kernel I/O: O_EXCL & pread
  3. 4.3 Descriptor Control: fcntl & ioctl

lab → Lab 4: Race-Free Positional Record Store with O_EXCL, pread/pwrite, and fcntl

GL-C01 · Linux Systems I/O & Buffering in C264/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Shared File Tables & dup Redirection

free preview25 min

What you'll learn

  • Compare the three Linux kernel file-sharing topologies across dual open(), dup/dup2/dup3, and fork() inheritance.
  • Reproduce independent-cursor overwrite hazards versus cooperating O_APPEND writes across dual open() descriptors.
  • Implement STDOUT_FILENO redirection and restoration while handling dup2(fd, fd) vs dup3(fd, fd, O_CLOEXEC) EINVAL.
GL-C01 · Linux Systems I/O & Buffering in C265/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails

  • Two subtle bugs surface whenever subsystems share files or redirect standard streams.
GL-C01 · Linux Systems I/O & Buffering in C266/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails

  • Predicting every multi-descriptor interaction in Linux requires tracing exactly which tier of the three-tab…
GL-C01 · Linux Systems I/O & Buffering in C267/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Mental model

note: Opening a file twice is like giving two editors separate bookmarks inside the same shared binder, whereas duplicating a descriptor clips two string tags onto a single shared bookmark that moves whenever either editor turns a page.

Where it stops working: Physical binder pages show ink collisions visually, whereas two independent kernel file descriptions overwrite cached bytes in RAM without warning unless O_APPEND serializes writes.

GL-C01 · Linux Systems I/O & Buffering in C268/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Dual-Open Independence vs Descriptor Aliasing (dup/dup2/dup3)

definition: Dual open() Topology: Calling open() twice on one pathname allocates two distinct struct file objects (f_count = 1 each, independent f_pos and f_flags) pointing to one shared struct inode. Descriptor Duplication (dup, dup2, dup3): Named for "duplicate file descriptor" in early Unix, dup*() allocates or rebinds a files_struct slot to point at the exact same struct file (atomic_long_inc(&file->f_count)), sharing f_pos and f_flags (O_APPEND, O_NONBLOCK) while keeping slot-level FD_CLOEXEC independent per descriptor integer.

GL-C01 · Linux Systems I/O & Buffering in C269/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails

ast_m04_l01_dual_open.svg

Figure 4.1a: Same-process dual open() — fd1 and fd2 allocate independent struct file cursors pointing to one shared VFS inode.

GL-C01 · Linux Systems I/O & Buffering in C270/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Why Dual open() Overwrites Data & dup3(fd, fd, O_CLOEXEC) Fails

fig_m04_l01_cross_proc.svg

Figure 4.1b: Two independent processes opening the same pathname — separate PCBs and separate struct file cursors share one VFS inode.

GL-C01 · Linux Systems I/O & Buffering in C271/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps

  • Inside task_struct->files->fdt, close_on_exec is a per-descriptor bitmask stored alongside fd_array[]…
GL-C01 · Linux Systems I/O & Buffering in C272/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps

fig_m04_l01_dup.svg

Figure 4.1c: dup() / dup2() / dup3() — two descriptor slots alias one shared struct file cursor (f_count = 2) while keeping FD_CLOEXEC isolated per slot.

GL-C01 · Linux Systems I/O & Buffering in C273/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps

Flush stdout first and call saved_out = dup(STDOUT_FILENO) to increment the terminal struct file's f_count to 2.

Only open() allocates a fresh struct file cursor; dup/dup2/dup3 alias an existing struct file, and safe STDOUT redirection flushes before and after rebinding.

GL-C01 · Linux Systems I/O & Buffering in C274/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

One Layer Down: f_count Reference Math & Per-Slot FD_CLOEXEC Bitmaps

fig_m04_l01_arch.svg

Figure 4.1d: Kernel descriptor-to-file-to-inode topologies across dual open(), dup/dup2/dup3, fork(), and leak-free STDOUT redirection.

GL-C01 · Linux Systems I/O & Buffering in C275/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

dup(2) / dup2(2) / dup3(2) Contracts & Safe STDOUT_FILENO Redirection

  • Define #define _GNU_SOURCE before <unistd.h> and <fcntl.h> on Linux 6.12 to expose dup3().
GL-C01 · Linux Systems I/O & Buffering in C276/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Proving Dual-Open Overwrites, dup3 Slot Isolation & stdout Restore

  • Save dual_open_dup.c below.
GL-C01 · Linux Systems I/O & Buffering in C277/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

dual_open_dup.c

learner@ksa: ~/gl-c01/m04-l01
learner@ksa:~/gl-c01/m04-l01$ bat dual_open_dup.c File: dual_open_dup.c    #define _GNU_SOURCE    #include <errno.h>    #include <fcntl.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <unistd.h>        static int has_cloexec_fdinfo(int target_fd) {        char p[64], buf[256];        snprintf(p, sizeof(p), "/proc/self/fdinfo/%d", target_fd);        int ifd = open(p, O_RDONLY | O_CLOEXEC);        if (ifd < 0) return 0;
GL-C01 · Linux Systems I/O & Buffering in C278/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Cursor Topologies and Clean Redirection Restore

  • Compile and execute dual_open_dup: confirm dual_no_append clobbers down to 8 bytes (BBBBBBBB), `dua…
GL-C01 · Linux Systems I/O & Buffering in C279/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Verifying Cursor Topologies and Clean Redirection Restore

learner@ksa: ~/gl-c01/m04-l01
learner@ksa:~/gl-c01/m04-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror dual_open_dup.c -o dual_open_duplearner@ksa:~/gl-c01/m04-l01./dual_open_duplearner@ksa:~/gl-c01/m04-l01test ! -e /tmp/ksa_m04_l01_over.bin && test ! -e /tmp/ksa_m04_l01_app.bin && rm -f dual_open_dupdual_no_append: bytes=8 payload=BBBBBBBBdual_o_append:  bytes=16 payload=AABBAABBAABBAABBdup_cursor: shared_f_pos=8 dup2_self=noop dup3_self_einval=yes cloexec=0/1redir_restored: captured=KSA-DUP|STDOUT_CAPTUREDlearner@ksa:~/gl-c01/m04-l01
GL-C01 · Linux Systems I/O & Buffering in C280/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Tracing f_count Lifetimes Across Redirection Boundaries

  • Notice how dup2(fd, STDOUT_FILENO) atomically closed descriptor 1's terminal reference and bound slot `…
GL-C01 · Linux Systems I/O & Buffering in C281/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Guided Practice: Writing a Self-Safe move_fd_cloexec() Helper

  • Write a helper int move_fd_cloexec(int src_fd, int dst_fd) that moves src_fd onto dst_fd with `FD_CLO…
GL-C01 · Linux Systems I/O & Buffering in C282/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Guided Practice: Writing a Self-Safe move_fd_cloexec() Helper

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C283/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Independent Practice: Combined stdout + stderr (2>&1) Capture Harness

  • Write a C11 test harness capture_both.c (-std=c11 -Wall -Wextra -Werror) that mimics shell `> combined.…
GL-C01 · Linux Systems I/O & Buffering in C284/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: Redirected printf() text prints onto the terminal after calling dup2(saved_out, STDOUT_FILENO) instead of landing inside the target file! Root Cause: When redirected to a regular file, stdout buffers output inside glibc RAM (_IOFBF); restoring descriptor 1 before calling fflush(stdout) flushes those buffered bytes onto the restored terminal descriptor. Fix: Call fflush(stdout) both before redirecting STDOUT_FILENO and immediately before restoring saved_out.

GL-C01 · Linux Systems I/O & Buffering in C285/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: dup3(fd, target_fd, O_CLOEXEC) fails sporadically in daemon startup tests with errno == EINVAL. Root Cause: Whenever target_fd was previously closed, open() may allocate fd == target_fd, and Linux dup3() explicitly rejects oldfd == newfd with EINVAL. Fix: Guard if (fd != target_fd) around dup3() + close(fd), and set FD_CLOEXEC via fcntl(fd, F_SETFD, FD_CLOEXEC) on the fd == target_fd branch.

GL-C01 · Linux Systems I/O & Buffering in C286/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

A single process calls fd1 = open("audit.bin", O_RDWR) on an existing 64-byte file, then calls fd2 = open("audit.bin", O_RDWR) without O_APPEND. After write(fd1, "ABCD", 4), what does lseek(fd2, 0, SEEK_CUR) return?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C287/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

You duplicate fd1 onto fd2 via dup3(fd1, fd2, O_CLOEXEC) where fd1 was opened without O_CLOEXEC. Which properties are shared between fd1 and fd2, and which remain separate?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C288/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) Suppose fd1 = dup(fd0) aliases a regular file at offset 0, and write(fd0, buf, 16) returns a short count of 10 bytes before a signal interrupts transfer. How must a retry write on fd1 proceed?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C289/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Quick check

What is the exact runtime difference between dup2(5, 5) and dup3(5, 5, O_CLOEXEC) when descriptor 5 is a valid open file?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C290/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Summary

  • Two open() calls on the same path create two independent struct file entries with separate f_pos cursors over one shared struct inode and page cache.
  • dup(), dup2(), and dup3() bind multiple descriptor integers to one struct file, sharing f_pos and f_flags while keeping FD_CLOEXEC private to each descriptor slot.
  • dup2(fd, fd) is a safe no-op returning fd, whereas dup3(fd, fd, O_CLOEXEC) returns -1 with errno == EINVAL.
  • Redirecting STDOUT_FILENO safely requires saving slot 1 via dup(), flushing stdout before and after redirection, restoring via dup2(), and closing the saved duplicate.
GL-C01 · Linux Systems I/O & Buffering in C291/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Summary

  • Next, we eliminate multi-process creation races (TOCTOU) and multithreaded shared-cursor races using `O_C…
GL-C01 · Linux Systems I/O & Buffering in C292/515

GL-C01 · 4.1 (m04-l01)

>_ Kernel Systems Academy

Key takeaways

  • dup2(fd, fd) is a safe no-op returning fd, whereas dup3(fd, fd, O_CLOEXEC) returns -1 with errno == EINVAL.
  • Redirecting STDOUT_FILENO safely requires saving slot 1 via dup(), flushing stdout before and after redirection, restoring via dup2(), and closing the saved duplicate.
  • Next, we eliminate multi-process creation races (TOCTOU) and multithreaded shared-cursor races using O_CREAT | O_EXCL, directory-pinned openat(), and stateless pread() / pwrite().
GL-C01 · Linux Systems I/O & Buffering in C293/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Atomic Kernel I/O: O_EXCL & pread

free preview25 min

What you'll learn

  • Diagnose preemption TOCTOU races (access + open) and cursor-clobber races (lseek + write) across workers.
  • Enforce atomic exclusive creation with O_CREAT | O_EXCL and directory-pinned openat(dirfd, ...) VFS lookups.
  • Execute stateless positional transfers via pread() and pwrite() while verifying struct file.f_pos stays unchanged.
GL-C01 · Linux Systems I/O & Buffering in C294/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Why Two-Syscall Sequences Fail Under Preemption

  • On a preemptive Symmetric Multiprocessing (SMP) Linux kernel, a hardware timer interrupt or higher-priori…
GL-C01 · Linux Systems I/O & Buffering in C295/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Why Two-Syscall Sequences Fail Under Preemption

  • User-space mutexes cannot coordinate independent processes, and two-syscall sequences cannot close kernel p…
GL-C01 · Linux Systems I/O & Buffering in C296/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Mental model

note: Calling lseek() and then write() on a shared descriptor is like shouting a shelf coordinate across a busy warehouse and hoping nobody shouts another coordinate before your crate lands; pwrite() stamps the exact bay coordinate directly onto the crate.

Where it stops working: Physical warehouse bays block two crates mechanically, whereas concurrent pwrite calls targeting overlapping byte offsets still race unless callers partition fixed-size slots or synchronize access.

GL-C01 · Linux Systems I/O & Buffering in C297/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

TOCTOU, Positional I/O (pread/pwrite) & Directory-Pinned *at() Calls

definition: Time-Of-Check to Time-Of-Use (TOCTOU) & O_CREAT | O_EXCL: Named in 1970s operating-system security audits for races between verifying a pathname precondition and acting on it, open(..., O_CREAT | O_EXCL, mode) tests dentry absence and allocates the inode atomically under the parent directory's i_rwsem lock (never following a terminal symlink). Positional I/O (pread / pwrite): Transfers bytes at an explicit off_t offset via stack-local kiocb.ki_pos without reading or modifying struct file.f_pos. Directory-Pinned *at() Calls (openat, renameat, unlinkat): Anchor relative lookups to a verified O_DIRECTORY dirfd so intermediate directory prefixes cannot be swapped mid-flight.

GL-C01 · Linux Systems I/O & Buffering in C298/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Why Two-Syscall Sequences Fail Under Preemption

fig_m04_l02_arch.svg

Figure 4.2a: Scheduler preemption between lseek() and write() clobbers shared cursors; stateless pread()/pwrite() and directory-pinned *at() calls close race windows.

GL-C01 · Linux Systems I/O & Buffering in C299/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Why Two-Syscall Sequences Fail Under Preemption

ast_m04_l02_excl_race.svg

Figure 4.2b: Time-of-check-to-time-of-use file-creation race between two processes versus atomic O_CREAT | O_EXCL.

GL-C01 · Linux Systems I/O & Buffering in C300/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

One Layer Down: kiocb.ki_pos vs f_pos_lock & Retry Offset Math

  • Look inside fs/read_write.c (ksys_pread64 vs ksys_read) to see why pread() scales linearly across…
GL-C01 · Linux Systems I/O & Buffering in C301/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

One Layer Down: kiocb.ki_pos vs f_pos_lock & Retry Offset Math

Pin an O_DIRECTORY descriptor dfd and create staging files via openat(..., O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600).

Fuse check-and-act inside single atomic kernel syscalls: openat(O_CREAT|O_EXCL), stateless pread/pwrite, and renameat + fsync(dfd).

GL-C01 · Linux Systems I/O & Buffering in C302/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

pread(2) / pwrite(2) Reference & the Linux O_APPEND Quirk

  • Define #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 before <unistd.h> and `<fcntl…
GL-C01 · Linux Systems I/O & Buffering in C303/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

pread

pread(2) at a glance — GL-C01
pread(2)                    GL-C01 Quick Reference                    pread(2) NAME       pread, pwrite - read from or write to a descriptor at a given offset SYNOPSIS       #define _POSIX_C_SOURCE 200809L       #include <unistd.h>       ssize_t pread(int fd, void *buf, size_t count, off_t offset);       ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset); STANDARDS       POSIX.1-2008; maps to pread64 / pwrite64 syscalls on Linux. RETURN VALUE       Returns bytes transferred (>= 0; 0 on pread means EOF), or -1 on error.       The file offset (struct file.f_pos) is NOT changed. ERRORS       EBADF  fd is not valid or not open for the requested direction. Kernel Systems Academy                    m04-l02                     pread(2) GL-C01 quick reference · full manual page: man 2 pread 
GL-C01 · Linux Systems I/O & Buffering in C304/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Reproducing Cursor Races vs Stateless pread/pwrite & atomic_replace_at

  • Save atomic_idioms.c below.
GL-C01 · Linux Systems I/O & Buffering in C305/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

atomic_idioms.c

learner@ksa: ~/gl-c01/m04-l02
learner@ksa:~/gl-c01/m04-l02$ bat atomic_idioms.c File: atomic_idioms.c    #define _FILE_OFFSET_BITS 64    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <unistd.h>        static int pwrite_full(int fd, const void *buf, size_t len, off_t off) {        const uint8_t *p = (const uint8_t *)buf;        size_t done = 0U;        while (done < len) {
GL-C01 · Linux Systems I/O & Buffering in C306/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Verifying Stateless pread64/pwrite64 Under strace

  • Compile and run atomic_idioms, verify racy_lseek vs atomic_pio (parked_f_pos=4) and replace_at=1,…
GL-C01 · Linux Systems I/O & Buffering in C307/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Verifying Stateless pread64/pwrite64 Under strace

learner@ksa: ~/gl-c01/m04-l02
learner@ksa:~/gl-c01/m04-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror atomic_idioms.c -o atomic_idiomslearner@ksa:~/gl-c01/m04-l02./atomic_idiomslearner@ksa:~/gl-c01/m04-l02test ! -e /tmp/ksa_m04_l02.lock && test ! -e /tmp/ksa_m04_l02_slots.binexcl_create: second_ret=-1 eexist=yesracy_lseek: slot0=00000000 unexpected_size=24atomic_pio: s0=SLOT0_OK s1=SLOT1_OK parked_f_pos=4atomic_append: bytes=9 log=REC1|REC2 replace_at=1learner@ksa:~/gl-c01/m04-l02
GL-C01 · Linux Systems I/O & Buffering in C308/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Verifying Stateless pread64/pwrite64 Under strace

  • Under strace, observe O_CREAT|O_EXCL returning -1 EEXIST on the second lock attempt and pwrite64/`p…
GL-C01 · Linux Systems I/O & Buffering in C309/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Verifying Stateless pread64/pwrite64 Under strace

strace — learner@ksa: ~/gl-c01/m04-l02
learner@ksa:~/gl-c01/m04-l02strace -e trace=openat,pwrite64,pread64,unlink,unlinkat,close ./atomic_idioms
GL-C01 · Linux Systems I/O & Buffering in C310/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

How Kernel i_rwsem and Stateless kiocb Close Race Windows

  • Every race in atomic_idioms disappeared as soon as check-and-use moved inside one kernel boundary: `O_CRE…
GL-C01 · Linux Systems I/O & Buffering in C311/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Guided Practice: Writing pread_full() with Short-Count & EOF Handling

  • Complete the companion helper ssize_t pread_full(int fd, void *buf, size_t len, off_t off) matching `pwri…
GL-C01 · Linux Systems I/O & Buffering in C312/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Guided Practice: Writing pread_full() with Short-Count & EOF Handling

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C313/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Independent Practice: renameat2(..., RENAME_NOREPLACE) Lockless Publisher

  • On Linux 3.15+ (#define _GNU_SOURCE), renameat2(dfd, tmp_name, dfd, target_name, RENAME_NOREPLACE) atom…
GL-C01 · Linux Systems I/O & Buffering in C314/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: Calling pwrite(fd, &super_hdr, 64, 0) on Linux to overwrite a file header at offset 0 silently appends super_hdr to the end of the file instead! Root Cause: On Linux (deviating from strict POSIX), if fd was opened with O_APPEND, pwrite() ignores its offset parameter and forces every write to i_size. Fix: Open descriptors used for positional pwrite() updates without O_APPEND (or maintain a separate non-append header descriptor).

GL-C01 · Linux Systems I/O & Buffering in C315/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: Guarding daemon lockfile creation with if (access(lock_path, F_OK) != 0) open(lock_path, O_WRONLY | O_CREAT, 0600); allows two daemon instances to start concurrently or follow an attacker-planted symlink. Root Cause: Scheduler preemption between access() and open() creates a TOCTOU race window, and open() without O_EXCL follows symlinks. Fix: Remove access() and execute a single openat(dfd, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600).

GL-C01 · Linux Systems I/O & Buffering in C316/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

Eight worker threads share one int fd opened with O_RDWR | O_CLOEXEC on an indexed record store (f_pos is currently 128). Thread 3 calls pread(fd, buf, 64, 4096) and reads 64 bytes. What is f_pos afterward?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C317/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

Two independent collector processes open /var/log/events.bin without O_APPEND and execute lseek(fd, 0, SEEK_END) followed by write(fd, rec, 32). Why do committed records randomly vanish under load?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C318/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) When pwrite(fd, buf, 4096, slot_off) returns a short count of 1024 bytes, how must a production C11 retry loop issue the next call?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C319/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Quick check

Why do security-hardened daemons replace path-string open("/tmp/work/cfg.tmp", ...) + rename() with an O_RDONLY | O_DIRECTORY | O_CLOEXEC directory descriptor (openat with O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, fdatasync(tfd), renameat(), and fsync(dfd))?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C320/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Summary

  • Any file invariant split across two user-space syscalls (access + open, or lseek + write) is vulnerable to kernel scheduler preemption races.
  • open(..., O_CREAT | O_EXCL, mode) fuses existence testing and inode creation into one atomic VFS directory operation failing with EEXIST on collision.
  • pread() and pwrite() transfer bytes at an explicit off_t coordinate without reading or mutating struct file.f_pos (provided O_APPEND is clear on Linux).
  • Opening log descriptors with O_APPEND serializes offset placement (ki_pos = i_size) and payload copy under inode->i_rwsem.
GL-C01 · Linux Systems I/O & Buffering in C321/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Summary

  • Next, we complete Module 4 by controlling live descriptors at runtime using fcntl() flag tiers, ABI-stabl…
GL-C01 · Linux Systems I/O & Buffering in C322/515

GL-C01 · 4.2 (m04-l02)

>_ Kernel Systems Academy

Key takeaways

  • Opening log descriptors with O_APPEND serializes offset placement (ki_pos = i_size) and payload copy under inode->i_rwsem.
  • Directory-pinned openat() (O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC) paired with fdatasync(tfd), renameat(), and fsync(dfd) closes path-prefix TOCTOU races and delivers crash-safe atomic replacement.
  • Next, we complete Module 4 by controlling live descriptors at runtime using fcntl() flag tiers, ABI-stable ioctl() structures, and ftruncate() file resizing.
GL-C01 · Linux Systems I/O & Buffering in C323/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Descriptor Control: fcntl & ioctl

free preview20 minlab lab_m04_atomic_kv

What you'll learn

  • Modify descriptor (FD_CLOEXEC) and mutable struct file flags (O_APPEND, O_NONBLOCK) via fcntl() and O_ACCMODE.
  • Validate ABI-stable ioctl() structs (_Static_assert, zeroed padding) alongside FIONREAD and TIOCGWINSZ ENOTTY.
  • Resize regular files with ftruncate() and truncate() while accounting for unchanged f_pos and zero-filled extensions.
GL-C01 · Linux Systems I/O & Buffering in C324/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Why Blind F_SETFL Wipes Flags & Sloppy ioctl Structs Fail With ENOTTY

  • Three runtime descriptor bugs ambush systems engineers regularly.
GL-C01 · Linux Systems I/O & Buffering in C325/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Why Blind F_SETFL Wipes Flags & Sloppy ioctl Structs Fail With ENOTTY

  • Controlling already-open descriptors cleanly requires respecting the VFS boundary between **Tier A per-slot…
GL-C01 · Linux Systems I/O & Buffering in C326/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Mental model

note: Using fcntl() and ioctl() on an open descriptor is like flipping circuit breakers on a live industrial valve panel without shutting down or unbolting the pipeline, while ftruncate() trims or extends the storage tank directly.

Where it stops working: Moving a tank wall physically pushes a floating gauge back inside bounds, whereas shrinking a file with ftruncate leaves f_pos stranded past the new end-of-file.

GL-C01 · Linux Systems I/O & Buffering in C327/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

fcntl() Flag Tiers, Out-of-Band ioctl() & ftruncate()

definition: File Control (fcntl): Standardized in POSIX <fcntl.h> as the runtime VFS multiplexer separating slot-local descriptor attributes (F_DUPFD_CLOEXEC, F_GETFD/F_SETFD for FD_CLOEXEC) from shared struct file.f_flags (F_GETFL/F_SETFL). Input/Output Control (ioctl) & ENOTTY: Named from Seventh Edition Unix teletype ("TTY") out-of-band control—which is why applying a terminal request like TIOCGWINSZ to a regular file or pipe still returns historical ENOTTY ("Not a typewriter")! ftruncate(fd, length): Resizes inode->i_size on a writable regular file without modifying struct file.f_pos.

GL-C01 · Linux Systems I/O & Buffering in C328/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

One Layer Down: 32-Bit _IOC Command Bitfields & F_SETFL Mask Rules

  • Inside <uapi/asm-generic/ioctl.h>, Linux packs four fields into every 32-bit _IO, _IOR, _IOW, and `…
GL-C01 · Linux Systems I/O & Buffering in C329/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

One Layer Down: 32-Bit _IOC Command Bitfields & F_SETFL Mask Rules

fig_m04_l03_arch.svg

Figure 4.3: 32-bit _IOC command bitfield encoding, fcntl() Tier A vs Tier B flag control, and ftruncate() cursor invariants.

GL-C01 · Linux Systems I/O & Buffering in C330/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

One Layer Down: 32-Bit _IOC Command Bitfields & F_SETFL Mask Rules

Clone or update per-slot FD_CLOEXEC via F_DUPFD_CLOEXEC and F_GETFD / F_SETFD without disturbing aliases.

Separate per-slot FD_CLOEXEC from read-modify-write F_SETFL status flags, lock ioctl struct sizes with _Static_assert, and reposition f_pos after ftruncate().

GL-C01 · Linux Systems I/O & Buffering in C331/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

fcntl(2) Quick Reference & Read-Modify-Write Discipline

  • Define #define _GNU_SOURCE and #define _FILE_OFFSET_BITS 64 before <fcntl.h>, <unistd.h>, and `<sys…
GL-C01 · Linux Systems I/O & Buffering in C332/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

fcntl

fcntl(2) at a glance — GL-C01
fcntl(2)                    GL-C01 Quick Reference                    fcntl(2) NAME       fcntl, ftruncate - manipulate file descriptor flags and inode size SYNOPSIS       #include <fcntl.h>       #include <unistd.h>       int fcntl(int fd, int cmd, ... /* arg */);       int ftruncate(int fd, off_t length); STANDARDS       POSIX.1-2008; F_DUPFD_CLOEXEC requires POSIX.1-2008 (_POSIX_C_SOURCE >=       200809L). RETURN VALUE       F_DUPFD* returns new fd; F_GETFD / F_GETFL return flags (>= 0);       F_SETFD, F_SETFL, and ftruncate() return 0 on success, or -1 on error. ERRORS       EBADF  fd is not an open descriptor (or not open for writing on              ftruncate). Kernel Systems Academy                    m04-l03                     fcntl(2) GL-C01 quick reference · full manual page: man 2 fcntl 
GL-C01 · Linux Systems I/O & Buffering in C333/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Probing fcntl Tiers, ABI-Verified ioctl & ftruncate Cursor Invariants

  • Save desc_ctl.c below.
GL-C01 · Linux Systems I/O & Buffering in C334/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

desc_ctl.c

learner@ksa: ~/gl-c01/m04-l03
learner@ksa:~/gl-c01/m04-l03$ bat desc_ctl.c File: desc_ctl.c    #define _GNU_SOURCE    #define _FILE_OFFSET_BITS 64    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/ioctl.h>    #include <sys/stat.h>    #include <unistd.h>        struct ksa_dev_cfg {        uint32_t rate_hz;
GL-C01 · Linux Systems I/O & Buffering in C335/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Verifying Flag Bitmasks, FIONREAD, ftruncate & Lab 4

  • Compile desc_ctl.c, pipe a 19-byte payload (TELEMETRY_PING_2026) into STDIN_FILENO, verify every outp…
GL-C01 · Linux Systems I/O & Buffering in C336/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Verifying Flag Bitmasks, FIONREAD, ftruncate & Lab 4

learner@ksa: ~/gl-c01/m04-l03
learner@ksa:~/gl-c01/m04-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror desc_ctl.c -o desc_ctllearner@ksa:~/gl-c01/m04-l03printf 'TELEMETRY_PING_2026' | ./desc_ctllearner@ksa:~/gl-c01/m04-l03test ! -e /tmp/ksa_m04_l03.dat && rm -f desc_ctlfcntl_state: hi_ge40=yes cloexec=0->1 acc=O_RDWR append=1ioctl_probe: pipe_fionread=19 winsize_enotty=yes ioc_sz=16resize_check: shrunk=16 f_pos=32->32 ext=64 zero=0learner@ksa:~/gl-c01/m04-l03
GL-C01 · Linux Systems I/O & Buffering in C337/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Lab: lab_m04_atomic_kv

  • 1.

Verify: ./check.sh exits 0.

GL-C01 · Linux Systems I/O & Buffering in C338/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Kernel Mechanics Across fcntl, ioctl & Inode Resizing

  • In desc_ctl, F_DUPFD_CLOEXEC scanned files_struct starting at slot 40 and set FD_CLOEXEC atomical…
GL-C01 · Linux Systems I/O & Buffering in C339/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Guided Practice: Safe Read-Modify-Write set_nonblocking() Helper

  • Write a reusable helper int set_nonblocking(int fd, int enable) that sets or clears O_NONBLOCK without…
GL-C01 · Linux Systems I/O & Buffering in C340/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Guided Practice: Safe Read-Modify-Write set_nonblocking() Helper

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C341/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Independent Practice: _IOC Bitfield Decoder & Struct ABI Auditor

  • Write a C11 utility ioctl_decode.c (-std=c11 -Wall -Wextra -Werror) that takes three real Linux ioctl…
GL-C01 · Linux Systems I/O & Buffering in C342/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Calling fcntl(fd, F_SETFL, O_NONBLOCK) on an active shared log file silently disables O_APPEND, causing log lines to overwrite offset 0! Root Cause: F_SETFL overwrites all mutable status bits in struct file.f_flags rather than setting a single bit. Fix: Always execute read-modify-write: int fl = fcntl(fd, F_GETFL); if (fl != -1) fcntl(fd, F_SETFL, fl | O_NONBLOCK);.

GL-C01 · Linux Systems I/O & Buffering in C343/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Resetting a 4,096-byte state file via ftruncate(fd, 0) and immediately calling write(fd, hdr, 32) (without O_APPEND) produces a 4,128-byte file starting with 4,096 zero bytes! Root Cause: ftruncate() updates inode->i_size to 0 while leaving struct file.f_pos stranded at 4096, turning the next sequential write() into a sparse-hole extension. Fix: Call lseek(fd, 0, SEEK_SET) right after ftruncate(), or write via pwrite(fd, hdr, 32, 0).

GL-C01 · Linux Systems I/O & Buffering in C344/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

Given int fl = fcntl(fd, F_GETFL); (fl != -1), which expression correctly tests whether fd was opened read-only (O_RDONLY)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C345/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

Which set of flags can be modified at runtime on an already-open Linux file descriptor via fcntl(fd, F_SETFL, new_flags)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C346/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) You duplicate fd1 to fd2 = fcntl(fd1, F_DUPFD_CLOEXEC, 10) and then call fcntl(fd1, F_SETFL, fl | O_NONBLOCK). What is the resulting state of fd2?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C347/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Quick check

Why does placing unsigned long or unnamed compiler padding inside a custom _IOWR('k', 0x11, struct cfg) ioctl payload break 32-bit ARMv7 user binaries on a 64-bit kernel (ENOTTY) and risk data leaks?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C348/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Summary

  • fcntl() separates per-descriptor slot control (F_DUPFD_CLOEXEC, F_GETFD/F_SETFD for FD_CLOEXEC) from shared struct file status flags (F_GETFL/F_SETFL).
  • F_SETFL toggles O_APPEND, O_NONBLOCK, O_ASYNC, O_DIRECT, and O_NOATIME via read-modify-write, while (flags & O_ACCMODE) remains immutable after open().
  • ioctl() dispatches out-of-band driver and subsystem queries (FIONREAD, TIOCGWINSZ) and fails with ENOTTY on unsupported file types.
  • Custom _IOR/_IOW/_IOWR UAPI structs encode sizeof(struct) into _IOC_SIZE(cmd), requiring <stdint.h> fixed-width fields, explicit reserved padding, memset(), and _Static_assert.
GL-C01 · Linux Systems I/O & Buffering in C349/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Summary

  • Having mastered raw kernel descriptors across Modules 1–4, Module 5 steps back into Ring 3 to dissect how…
GL-C01 · Linux Systems I/O & Buffering in C350/515

GL-C01 · 4.3 (m04-l03)

>_ Kernel Systems Academy

Key takeaways

  • Custom _IOR/_IOW/_IOWR UAPI structs encode sizeof(struct) into _IOC_SIZE(cmd), requiring <stdint.h> fixed-width fields, explicit reserved padding, memset(), and _Static_assert.
  • ftruncate() (requiring a writable fd) and truncate() resize inode->i_size without modifying struct file.f_pos.
  • Having mastered raw kernel descriptors across Modules 1–4, Module 5 steps back into Ring 3 to dissect how glibc <stdio.h> FILE streams amortize syscall traps, handle binary fread/fwrite tails, and parse text safely.
GL-C01 · Linux Systems I/O & Buffering in C351/515

m05/

>_ Kernel Systems Academy

Standard C Library (stdio) Streams & Formatted I/O

Map glibc FILE streams and fopen mode strings to kernel openat flags, serialize fixed binary records safely with fread/fwrite/fseeko and feof/ferror triage, and construct truncation-safe snprintf and fgets/strtol codecs.

  1. 5.1 Standard I/O Streams & fopen Modes
  2. 5.2 Binary Stream I/O, fseeko & EOF
  3. 5.3 Bounded snprintf & Safe Text Parsing

lab → Lab 5: Bounded stdio Sensor Log Parser & Binary Codec

GL-C01 · Linux Systems I/O & Buffering in C352/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Standard I/O Streams & fopen Modes

free preview20 min

What you'll learn

  • Analyze how glibc FILE control blocks amortize Ring 3-to-Ring 0 syscall traps above raw integer file descriptors.
  • Translate every C11 and glibc fopen() mode string (b, e, x) to its exact openat() kernel flag bitmask.
  • Verify stdin/stdout/stderr descriptor bindings, open_memstream() buffers, and checked fclose() error handling.
GL-C01 · Linux Systems I/O & Buffering in C353/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Why Raw Syscalls Stall Tiny Writes & Plain "w+" Opens Races

  • Suppose a high-rate telemetry collector formats 4,096 four-byte voltage samples per batch and emits each…
GL-C01 · Linux Systems I/O & Buffering in C354/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Why Raw Syscalls Stall Tiny Writes & Plain "w+" Opens Races

  • High-throughput, leak-free stream I/O requires understanding how glibc's user-space FILE control block…
GL-C01 · Linux Systems I/O & Buffering in C355/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Mental model

note: Using raw syscalls for tiny writes is like carrying individual parcels across a guarded border checkpoint one by one, whereas a stdio FILE stream packs parcels into a user-space crate and crosses the border only when the crate fills.

Where it stops working: A physical crate sitting in your warehouse survives a building power cut, whereas bytes held inside a user-space FILE buffer vanish if the process crashes or calls _exit() before flushing.

GL-C01 · Linux Systems I/O & Buffering in C356/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Standard I/O Stream (FILE), Mode Extensions & Memory Streams

definition: Standard I/O Stream (FILE): Introduced by Mike Lesk and Dennis Ritchie in the Portable I/O Library (<stdio.h>), FILE (struct _IO_FILE in glibc) is an opaque Ring 3 control block wrapping an underlying _fileno descriptor with user-space _IO_read_ptr/_IO_write_ptr heap buffers, an internal mutex lock, and sticky EOF/error bits. glibc Mode Extensions ("e", "x"): Append O_CLOEXEC ("e") and O_EXCL ("x") to the initial openat() syscall. Memory Streams (open_memstream, fmemopen): Standardized in POSIX.1-2008 to bind FILE * virtual-function tables directly onto heap or caller RAM (fileno() == -1, EBADF).

GL-C01 · Linux Systems I/O & Buffering in C357/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math

  • Inside glibc (libio/bits/types/struct_FILE.h), writing s bytes via fwrite() or fputs() checks whe…
GL-C01 · Linux Systems I/O & Buffering in C358/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math

fig_m05_l01_arch.svg

Figure 5.1: User-space glibc struct _IO_FILE state, open_memstream() vtables, and exact fopen() mode-to-openat() flag translations.

GL-C01 · Linux Systems I/O & Buffering in C359/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

One Layer Down: _IO_FILE Cursor Pointers & Syscall Amortization Math

Open streams with glibc 'e' (O_CLOEXEC) and 'x' (O_EXCL) suffixes inside a single atomic openat() syscall.

Append glibc 'e' and 'x' safety suffixes on fopen(), batch tiny records in Ring 3 heap RAM, and always check fclose(fp) == 0.

GL-C01 · Linux Systems I/O & Buffering in C360/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Stream Headers, Checked fclose() & open_memstream()

  • Define #define _POSIX_C_SOURCE 200809L before <stdio.h>, <fcntl.h>, <time.h>, and <unistd.h> so `…
GL-C01 · Linux Systems I/O & Buffering in C361/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Probing fopen Kernel Flags, open_memstream & Amortization Speedup

  • Save fopen_modes_probe.c below.
GL-C01 · Linux Systems I/O & Buffering in C362/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

fopen_modes_probe.c

learner@ksa: ~/gl-c01/m05-l01
learner@ksa:~/gl-c01/m05-l01$ bat fopen_modes_probe.c File: fopen_modes_probe.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <time.h>    #include <unistd.h>        static uint64_t diff_ns(struct timespec a, struct timespec b) {        return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL +               (uint64_t)(b.tv_nsec - a.tv_nsec);
GL-C01 · Linux Systems I/O & Buffering in C363/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Verifying Stream Flags, Memory Streams & Amortization Speedup

  • Compile and execute fopen_modes_probe: confirm std_streams (0, 1, 2), "w+xe" (O_RDWR, `FD_CLOEXEC…
GL-C01 · Linux Systems I/O & Buffering in C364/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Verifying Stream Flags, Memory Streams & Amortization Speedup

learner@ksa: ~/gl-c01/m05-l01
learner@ksa:~/gl-c01/m05-l01gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror fopen_modes_probe.c -o fopen_modes_probelearner@ksa:~/gl-c01/m05-l01./fopen_modes_probelearner@ksa:~/gl-c01/m05-l01test ! -e /tmp/ksa_m05_l01.log && rm -f fopen_modes_probestd_streams: in=0 out=1 err=2mode_wplus_xe: wpe_ok=1 acc=O_RDWR append=0 cloexec=1 wx=1mode_aplus_e: acc=O_RDWR append=1 cloexec=1 bytes=11 mem=1 buf_faster=1learner@ksa:~/gl-c01/m05-l01
GL-C01 · Linux Systems I/O & Buffering in C365/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Inside glibc fopen(), Buffer Flush & open_memstream()

  • When fopen(path, "w+xe") executed, glibc allocated struct _IO_FILE on the heap and called `openat(AT_…
GL-C01 · Linux Systems I/O & Buffering in C366/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Guided Practice: Auditing fopen Mode Strings for strace Verification

  • Predict the exact openat() flag mask printed by strace -e trace=openat for each of the following three…
GL-C01 · Linux Systems I/O & Buffering in C367/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Guided Practice: Auditing fopen Mode Strings for strace Verification

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C368/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Independent Practice: Zero-File fmemopen() & open_memstream() Unit Test

  • Write a C11 test memstream_roundtrip.c (-std=c11 -Wall -Wextra -Werror) containing a serializer `int wr…
GL-C01 · Linux Systems I/O & Buffering in C369/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: A multithreaded service opens configuration streams via fopen(path, "w+") and leaks open descriptors across fork() + execve() into child processes, or clobbers files created concurrently. Root Cause: Standard C "w+" omits O_CLOEXEC and O_EXCL. Fix: Append glibc's "e" modifier ("re", "w+e", "ae") on all Linux daemon streams, and add "x" ("wxe", "w+xe") for atomic exclusive file creation.

GL-C01 · Linux Systems I/O & Buffering in C370/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: Small fputs() writes return >= 0 without error, yet disk-full (ENOSPC) corruption goes completely undetected because the caller wrote fclose(fp); without checking its return code! Root Cause: Buffered writes stay in Ring 3 RAM until the buffer fills or fclose(fp) flushes remaining bytes via write(), reporting ENOSPC or EIO only through fclose() returning EOF (-1). Fix: Always treat if (fclose(fp) != 0) on writable streams as an I/O failure.

GL-C01 · Linux Systems I/O & Buffering in C371/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

Which openat() flag bitmask does glibc pass to the Linux kernel when you call fopen("/var/log/app.log", "a+e")?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C372/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

Why does fopen("capture.bin", "rb") behave identically to fopen("capture.bin", "r") on Linux?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C373/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) When fopen(path, "wxe") returns NULL with errno == EEXIST because a rival worker just created path, which kernel mechanism prevented a TOCTOU overwrite?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C374/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Quick check

You want to unit-test a C serializer int emit_frame(FILE *out) completely in RAM without creating /tmp files or allocating kernel descriptors. Which POSIX.1-2008 function creates a dynamically growing heap-backed FILE * stream?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C375/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Summary

  • glibc FILE streams wrap integer file descriptors with user-space _IO_read_ptr/_IO_write_ptr buffers and sticky status bits to amortize Ring 3-to-Ring 0 syscall overhead.
  • Every hosted C process starts with pre-opened stdin (0), stdout (1), and stderr (2) streams in <stdio.h>.
  • fopen() modes "r", "r+", "w", "w+", "a", and "a+" map deterministically to O_RDONLY/O_RDWR/O_WRONLY plus O_CREAT, O_TRUNC, or O_APPEND, while "b" is a POSIX no-op.
  • Linux glibc extensions "e" (O_CLOEXEC) and "x" (O_EXCL) close descriptor-leak and creation-race windows inside the initial openat(), and fclose(fp) must always be checked on writable streams.
GL-C01 · Linux Systems I/O & Buffering in C376/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Summary

  • Next, we serialize fixed-width binary structs over FILE * streams using item-counted fread()/fwrite()…
GL-C01 · Linux Systems I/O & Buffering in C377/515

GL-C01 · 5.1 (m05-l01)

>_ Kernel Systems Academy

Key takeaways

  • Linux glibc extensions "e" (O_CLOEXEC) and "x" (O_EXCL) close descriptor-leak and creation-race windows inside the initial openat(), and fclose(fp) must always be checked on writable streams.
  • POSIX.1-2008 open_memstream() and fmemopen() back FILE * streams directly with RAM (fileno() == -1, EBADF).
  • Next, we serialize fixed-width binary structs over FILE * streams using item-counted fread()/fwrite(), 64-bit fseeko()/ftello(), sticky feof()/ferror() triage, and 257-state int fgetc().
GL-C01 · Linux Systems I/O & Buffering in C378/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Binary Stream I/O, fseeko & EOF

free preview20 min

What you'll learn

  • Serialize and read fixed-width binary structs via item-counted fwrite()/fread() while recovering torn tail bytes.
  • Reposition 64-bit streams portably with fseeko(), ftello(), and rewind() across C11 + turnaround barriers.
  • Disambiguate short counts with feof(), ferror(), and int fgetc() without while (!feof(fp)) or 0xFF char bugs.
GL-C01 · Linux Systems I/O & Buffering in C379/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why while (!feof(fp)) & char c = fgetc(fp) Break Binary Readers

  • Three <stdio.h> bugs survive code review with alarming frequency.
GL-C01 · Linux Systems I/O & Buffering in C380/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why while (!feof(fp)) & char c = fgetc(fp) Break Binary Readers

  • Writing rock-solid binary stdio code requires mastering four exact contracts: item-counted fread/`fwrit…
GL-C01 · Linux Systems I/O & Buffering in C381/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Mental model

note: Calling fread(recs, sizeof(rec), K, fp) is like asking a bottling machine to fill K six-packs rather than counting individual bottles — if five loose bottles remain when the tank runs dry, the machine reports zero completed six-packs.

Where it stops working: A bottling line leaves partial bottles visible on the belt, whereas fread() leaves the partial record bytes indeterminate inside your destination buffer and advances the stream position across them.

GL-C01 · Linux Systems I/O & Buffering in C382/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Item-Counted I/O, Sticky Stream Indicators & 257-State EOF

definition: Item-Counted Stream I/O (fread / fwrite): Unlike raw read()/write() (ssize_t bytes), fread(ptr, size, nmemb, fp) returns size_t complete items (0..nmemb). 64-Bit Stream Offsets (fseeko / ftello): Replace ISO C long (32-bit on ILP32 ARMv7) with 64-bit off_t and enforce C11 "+" update-stream turnaround synchronization. Sticky Indicators (feof, ferror) & 257-State EOF: _IO_EOF_SEEN turns on only after a read attempts to cross EOF (persisting until clearerr/rewind/fseeko), while fgetc() returns unsigned char widened to int (0..255) plus negative EOF (-1)—257 states requiring an int variable.

GL-C01 · Linux Systems I/O & Buffering in C383/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()

  • Inside glibc (iofread.c), fread(ptr, size, nmemb, fp) computes requested bytes R = size * nmemb (ch…
GL-C01 · Linux Systems I/O & Buffering in C384/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()

  • Similarly, the Pigeonhole Principle explains why char can never hold fgetc(fp): every 8-bit byte `0…
GL-C01 · Linux Systems I/O & Buffering in C385/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()

fig_m05_l02_arch.svg

Figure 5.2: Item-counted fread() torn-tail division, C11 '+' stream turnaround barriers, and 257-state int fgetc() safety.

GL-C01 · Linux Systems I/O & Buffering in C386/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

One Layer Down: Torn-Tail Division Math & the Pigeonhole Proof for int fgetc()

Serialize fixed-width records verified with _Static_assert via fwrite() and track 64-bit offsets with ftello().

Drive binary loops on fread()'s item count, synchronize '+' turnarounds with 64-bit fseeko(), and always store fgetc() in an int.

GL-C01 · Linux Systems I/O & Buffering in C387/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

64-Bit Feature Macros & C11 Update-Stream ("+") Turnaround Rules

  • Place #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 at lines 1–2 before <stdio.h>…
GL-C01 · Linux Systems I/O & Buffering in C388/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Testing Torn Tails, Turnaround Barriers, 257-State fgetc & feof Timing

  • Save binary_stream_eof.c below.
GL-C01 · Linux Systems I/O & Buffering in C389/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

binary_stream_eof.c

learner@ksa: ~/gl-c01/m05-l02
learner@ksa:~/gl-c01/m05-l02$ bat binary_stream_eof.c File: binary_stream_eof.c    #define _POSIX_C_SOURCE 200809L    #define _FILE_OFFSET_BITS 64    #include <stdint.h>    #include <stdio.h>    #include <unistd.h>        struct sample_rec {        uint32_t seq;        int32_t mv;        uint64_t ts_ns;    };    _Static_assert(sizeof(struct sample_rec) == 16, "packed by natural alignment");        int main(void) {
GL-C01 · Linux Systems I/O & Buffering in C390/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Verifying Torn-Tail Counts, fgetc 257-State Safety & EOF Timing

  • Compile and run binary_stream_eof: observe items=3 (54 / 16), byte_tail recovering all 6 torn byt…
GL-C01 · Linux Systems I/O & Buffering in C391/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Verifying Torn-Tail Counts, fgetc 257-State Safety & EOF Timing

learner@ksa: ~/gl-c01/m05-l02
learner@ksa:~/gl-c01/m05-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror binary_stream_eof.c -o binary_stream_eoflearner@ksa:~/gl-c01/m05-l02./binary_stream_eoflearner@ksa:~/gl-c01/m05-l02test ! -e /tmp/ksa_m05_l02.bin && rm -f binary_stream_eofitem_read: total=54 items=3 eof=1 err=0 last_mv=3310byte_tail: cleared=1 bytes=6 hex0=AA fgetc_257=1eof_timing: loops=3 r3=3 exact=0 r4=0 past=1learner@ksa:~/gl-c01/m05-l02
GL-C01 · Linux Systems I/O & Buffering in C392/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Why Byte-Exact Tail Recovery Needs size = 1 or ftello()

  • Notice what happened when fread(out, 16, 4, fp) hit the 54-byte torn file: it returned 3 items, yet t…
GL-C01 · Linux Systems I/O & Buffering in C393/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Guided Practice: Detecting a Torn Struct Tail with size = 1

  • Rewrite the while (fread(&cur, sizeof(cur), 1, fp) == 1) loop so it distinguishes clean EOF from a…
GL-C01 · Linux Systems I/O & Buffering in C394/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Guided Practice: Detecting a Torn Struct Tail with size = 1

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C395/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Independent Practice: In-Place Binary Record Patcher on "r+be"

  • Write a C11 program patch_record.c (_FILE_OFFSET_BITS=64, -Wall -Wextra -Werror) that writes 5 `str…
GL-C01 · Linux Systems I/O & Buffering in C396/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: A binary parser written as while (!feof(fp)) { fread(&rec, sizeof(rec), 1, fp); emit(&rec); } emits the final record twice on every file and hangs infinitely on read errors (EIO). Root Cause: feof(fp) turns nonzero only after a read attempts to cross EOF, and never turns on when ferror(fp) halts input. Fix: Loop on while (fread(&rec, sizeof(rec), 1, fp) == 1) and test ferror(fp) vs feof(fp) once after the loop exits.

GL-C01 · Linux Systems I/O & Buffering in C397/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: Calling fwrite(&hdr, sizeof(hdr), 1, fp) followed immediately by fread(&rec, sizeof(rec), 1, fp) on a "w+" or "r+" stream returns stale or corrupted bytes. Root Cause: ISO C11 requires an explicit flush or positioning call when switching between output and input on an update ("+") stream so glibc synchronizes _IO_write_ptr and _IO_read_ptr. Fix: Insert fseeko(fp, target_off, SEEK_SET) (or fseeko(fp, 0, SEEK_CUR)) at every read/write turnaround.

GL-C01 · Linux Systems I/O & Buffering in C398/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

A file contains 38 bytes. You open it at offset 0 and call size_t n = fread(recs, 16, 4, fp);. What does fread() return, and what are feof(fp) and ferror(fp)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C399/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

Why should portable Linux C11 code prefer fseeko() and ftello() (under _FILE_OFFSET_BITS=64) over classic ISO C fseek() and ftell()?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C400/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) Suppose you truncate an open stream's backing file via fflush(fp); ftruncate(fileno(fp), 48);. Why must you still call rewind(fp) (or fseeko(fp, 0, SEEK_SET)) before reading from byte 0?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C401/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Quick check

A developer writes char c; while ((c = fgetc(fp)) != EOF) on x86-64 Linux, passes ASCII tests, and cross-compiles for 32-bit ARMv7 (Cortex-A7) Linux. What happens on each target when reading a binary file containing byte 0xFF?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C402/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Summary

  • fread() and fwrite() return counts of complete items (0..nmemb); use size = 1 for exact byte counts or size = sizeof(struct) for aligned fixed records.
  • fgetc() and getchar() return 257 int states (0..255 plus (int)-1 EOF); narrowing into char causes 0xFF false EOF on x86-64 and infinite loops on unsigned-char ARMv7.
  • Prefer 64-bit fseeko() and ftello() (off_t), and remember rewind(fp) resets both offset 0 and sticky feof/ferror flags.
  • On update ("+") streams, always insert fseeko() (or fflush() after writes) when switching between fwrite() and fread().
GL-C01 · Linux Systems I/O & Buffering in C403/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Summary

  • Next, we complete Module 5 by building truncation-safe snprintf() formatters (PRIu64, %zu) and fault-…
GL-C01 · Linux Systems I/O & Buffering in C404/515

GL-C01 · 5.2 (m05-l02)

>_ Kernel Systems Academy

Key takeaways

  • On update ("+") streams, always insert fseeko() (or fflush() after writes) when switching between fwrite() and fread().
  • Drive read loops with while (fread(...) == 1) rather than while (!feof(fp)), then inspect ferror(fp) vs feof(fp) once after termination.
  • Next, we complete Module 5 by building truncation-safe snprintf() formatters (PRIu64, %zu) and fault-isolated fgets() + strtol() line parsers.
GL-C01 · Linux Systems I/O & Buffering in C405/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Bounded snprintf & Safe Text Parsing

free preview20 minlab lab_m05_telemetry_codec

What you'll learn

  • Format fixed-width and pointer-sized integers portably (%zu, PRId64, PRIu64) via snprintf() with -Wformat clean.
  • Detect formatted output truncation deterministically by checking ret < 0 || (size_t)ret >= size on every snprintf().
  • Construct fault-isolated text parsers combining line-bounded fgets(), width-capped scansets, and ERANGE strtol().
GL-C01 · Linux Systems I/O & Buffering in C406/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Why Unchecked snprintf Accumulators & Raw fscanf Cause Exploits

  • Most C engineers know sprintf() is banned—yet a subtle snprintf() anti-pattern causes buffer overflows…
GL-C01 · Linux Systems I/O & Buffering in C407/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Why Unchecked snprintf Accumulators & Raw fscanf Cause Exploits

  • Bulletproof text formatting and parsing in C11 rest on three rules: checking snprintf()'s hypothetical-le…
GL-C01 · Linux Systems I/O & Buffering in C408/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Mental model

note: Calling sprintf() is like pouring hot metal into a mold with no overflow lip, whereas snprintf() caps the pour at the rim and reports the exact volume that would have filled an uncapped mold.

Where it stops working: Overflowed metal spills visibly onto the shop floor, whereas snprintf() silently truncates excess characters unless the caller checks whether the returned length is greater than or equal to the buffer capacity.

GL-C01 · Linux Systems I/O & Buffering in C409/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Bounded snprintf(), <inttypes.h> Macros & Scanset Framing

definition: snprintf(buf, size, fmt, ...) Return Contract (ISO C99/C11 §7.21.6.5): Writes at most size - 1 characters plus a guaranteed terminating '\0' (whenever size > 0), and returns int ret equal to the character count that would have been written excluding '\0' (ret < 0 on encoding error; (size_t)ret >= size if and only if output was truncated). Fixed-Width Format Macros (PRIu64, PRId64): String-literal macros in <inttypes.h> concatenated at compile time ("lu" on LP64 x86-64 vs "llu" on ILP32 ARMv7) so -Wformat -Werror stays clean across ABIs.

GL-C01 · Linux Systems I/O & Buffering in C410/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths

  • To append multiple formatted segments into char buf[CAP] at cursor size_t pos (0 <= pos < CAP), let r…
GL-C01 · Linux Systems I/O & Buffering in C411/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths

  • On input, notice the critical 1-byte asymmetry between fgets() and sscanf() width specifiers for `cha…
GL-C01 · Linux Systems I/O & Buffering in C412/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths

fig_m05_l03_arch.svg

Figure 5.3: Truncation-checked snprintf() accumulator math, <inttypes.h> specifiers, and fault-isolated fgets() + strtol() parsing.

GL-C01 · Linux Systems I/O & Buffering in C413/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths

Frame bounded lines with fgets(line, sizeof(line), fp) and check ferror(fp) vs feof(fp) on NULL exit.

Check (size_t)ret < rem before advancing snprintf() cursors, and isolate line framing with fgets() before tokenizing via (sizeof - 1) scansets and strtol().

GL-C01 · Linux Systems I/O & Buffering in C414/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

<inttypes.h> Specifiers, dprintf(3) & strtol(3) Validation

  • Include <stdio.h>, <stdlib.h>, <inttypes.h>, <stdint.h>, <limits.h>, and <errno.h> under `#defi…
GL-C01 · Linux Systems I/O & Buffering in C415/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Building a Truncation-Checked Formatter & Fault-Isolated Line Parser

  • Save fmt_safe_codec.c below.
GL-C01 · Linux Systems I/O & Buffering in C416/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

fmt_safe_codec.c

learner@ksa: ~/gl-c01/m05-l03
learner@ksa:~/gl-c01/m05-l03$ bat fmt_safe_codec.c File: fmt_safe_codec.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <inttypes.h>    #include <limits.h>    #include <stdarg.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <unistd.h>        static int buf_appendf(char *buf, size_t cap, size_t *pos,                           const char *fmt, ...) {
GL-C01 · Linux Systems I/O & Buffering in C417/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Verifying Truncation Math, Oversized-Line Draining & Lab 5

  • Compile and execute fmt_safe_codec: confirm req=28 vs cap=16 (trunc=1, app_guard=1), confirm `par…
GL-C01 · Linux Systems I/O & Buffering in C418/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Verifying Truncation Math, Oversized-Line Draining & Lab 5

learner@ksa: ~/gl-c01/m05-l03
learner@ksa:~/gl-c01/m05-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror fmt_safe_codec.c -o fmt_safe_codeclearner@ksa:~/gl-c01/m05-l03./fmt_safe_codeclearner@ksa:~/gl-c01/m05-l03test ! -e /tmp/ksa_m05_l03.txt && rm -f fmt_safe_codecsnprintf_check: req=28 cap=16 trunc=1 app_guard=1 prefix=ts=9000000001 iparser_check: ok=2 bad=3 sum_mv=3175learner@ksa:~/gl-c01/m05-l03
GL-C01 · Linux Systems I/O & Buffering in C419/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Lab: lab_m05_telemetry_codec

  • 1.

Verify: ./check.sh exits 0.

GL-C01 · Linux Systems I/O & Buffering in C420/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Why Line Isolation Outperforms Stream fscanf()

  • Look at how fgets() + strtol() isolated every failure mode in fmt_safe_codec: when the 52-byte `ove…
GL-C01 · Linux Systems I/O & Buffering in C421/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Guided Practice: Exact-Fit Dynamic String Allocation via snprintf(NULL, 0, ...)

  • Write a function char *format_alloc(const char *tag, uint64_t seq, ssize_t delta) that allocates an exact…
GL-C01 · Linux Systems I/O & Buffering in C422/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Guided Practice: Exact-Fit Dynamic String Allocation via snprintf(NULL, 0, ...)

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C423/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Independent Practice: Strict Key-Value Config Parser (strtoul Hex & Octal)

  • Write a C11 parser kv_cfg_check.c (-std=c11 -Wall -Wextra -Werror) that reads `"key = value # comment\n…
GL-C01 · Linux Systems I/O & Buffering in C424/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Chaining pos += snprintf(buf + pos, sizeof(buf) - pos, ...) without checking each return value overflows buf on the next call after truncation! Root Cause: snprintf() returns the needed length (>= sizeof(buf) - pos), pushing pos past sizeof(buf) and wrapping unsigned sizeof(buf) - pos near SIZE_MAX. Fix: Validate if (ret < 0 || (size_t)ret >= sizeof(buf) - pos) before every pos += (size_t)ret.

GL-C01 · Linux Systems I/O & Buffering in C425/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Writing char key[32]; sscanf(line, "%32s", key); overwrites 1 byte past key[31] on 32-character inputs (ASan stack-buffer-overflow). Root Cause: scanf/sscanf field widths count payload characters excluding the mandatory terminating '\0' byte (32 + 1 = 33 bytes). Fix: Always set scanf string/scanset widths to sizeof(buf) - 1 (%31s or %31[^,\n] for char[32]).

GL-C01 · Linux Systems I/O & Buffering in C426/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

Given char buf[10]; int r = snprintf(buf, sizeof(buf), "sensor_%04d", 42);, what value is stored in r, and what condition proves output truncated?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C427/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

Which format string portably prints a size_t byte count followed by a uint64_t timestamp across both 32-bit ARMv7 and 64-bit x86-64 Linux builds under -Wall -Werror?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C428/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) When fgets(line, sizeof(line), fp) returns NULL, how do you distinguish clean end-of-file from an underlying kernel read() fault?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C429/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Quick check

Why does production C11 text parsing prefer fgets() + strtol(num_s, &endp, 10) over fscanf(fp, "%d", &val) or atoi(num_s)?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C430/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Summary

  • Never call sprintf(); bound every formatted write with snprintf(buf, sz, ...) (or dprintf(fd, ...)) and check ret < 0 || (size_t)ret >= sz before advancing buffer offsets.
  • Pair size_t/ssize_t with %zu/%zd and 64-bit fixed integers with <inttypes.h> PRId64/PRIu64 so -Wformat -Werror builds cleanly across 32-bit and 64-bit targets.
  • Cap scanf/sscanf string and scanset widths at sizeof(buf) - 1 (%31[^\n] for char[32]) to reserve 1 byte for '\0'.
  • Parse text line-first via fgets() (draining oversized lines) + strtol() (endp and ERANGE checks) so malformed records never wedge the stream.
GL-C01 · Linux Systems I/O & Buffering in C431/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Summary

  • With both kernel descriptors and Ring 3 stdio streams in your toolkit, Module 6 unites both layers to m…
GL-C01 · Linux Systems I/O & Buffering in C432/515

GL-C01 · 5.3 (m05-l03)

>_ Kernel Systems Academy

Key takeaways

  • Cap scanf/sscanf string and scanset widths at sizeof(buf) - 1 (%31[^\n] for char[32]) to reserve 1 byte for '\0'.
  • Parse text line-first via fgets() (draining oversized lines) + strtol() (endp and ERANGE checks) so malformed records never wedge the stream.
  • With both kernel descriptors and Ring 3 stdio streams in your toolkit, Module 6 unites both layers to master kernel page-cache durability (fsync, fdatasync, O_DIRECT), two-stage fflush + fdatasync commits, and our capstone crash-safe CRC32 Write-Ahead Log!
GL-C01 · Linux Systems I/O & Buffering in C433/515

m06/

>_ Kernel Systems Academy

Two-Layer I/O Buffering, Durability & Capstone Engine

Master kernel page-cache writeback barriers (fsync, fdatasync, directory sync), sector-aligned O_DIRECT DMA, user-space setvbuf/fflush/fdopen ownership rules, and synthesize a crash-safe CRC32 Write-Ahead Log storage engine.

  1. 6.1 Page Cache, fsync & Direct I/O
  2. 6.2 stdio Buffering & Descriptor Interop
  3. 6.3 Capstone: Crash-Safe Binary Log

lab → Lab 6 Capstone: Crash-Consistent CRC32 Write-Ahead Log & KV Engine

GL-C01 · Linux Systems I/O & Buffering in C434/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Page Cache, fsync & Direct I/O

free preview20 min

What you'll learn

  • Distinguish SIGKILL survival in the volatile Linux kernel page cache from power-loss durability on storage media.
  • Select fsync(), fdatasync(), O_DSYNC, and parent-directory fsync(dir_fd) barriers for crash-consistent persistence.
  • Allocate STATX_DIOALIGN-aligned buffers via posix_memalign() for O_DIRECT DMA while handling tmpfs EINVAL.
GL-C01 · Linux Systems I/O & Buffering in C435/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Why write() Loses Data on Power Loss & rename() Needs Directory fsync

  • Two post-outage failures shock engineers who confuse process-crash survival with power-loss durability.
GL-C01 · Linux Systems I/O & Buffering in C436/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Why write() Loses Data on Power Loss & rename() Needs Directory fsync

  • Engineering crash-consistent storage on Linux requires distinguishing **process death (SIGKILL, where ker…
GL-C01 · Linux Systems I/O & Buffering in C437/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Mental model

note: A successful write() call is like handing a ledger entry to a clerk who pins it onto an erasable whiteboard in RAM; only fsync() or fdatasync() waits until the clerk engraves the entry onto non-volatile stone.

Where it stops working: Erasing a physical whiteboard loses everything in the room, whereas a user-space process crash (SIGSEGV or SIGKILL) leaves dirty kernel page-cache pages intact for normal background writeback.

GL-C01 · Linux Systems I/O & Buffering in C438/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Page Cache Writeback, fdatasync(), Dir Sync & O_DIRECT

definition: Page Cache Writeback: Buffered write() copies user bytes into inode->i_mapping XArray folios marked PG_dirty and governed by vm.dirty_background_ratio (10%) and vm.dirty_ratio (20%). fsync(fd) vs fdatasync(fd): fsync() flushes dirty data folios plus all inode metadata (mtime, ctime, i_size) and issues a storage controller cache flush (REQ_PREFLUSH / NVMe Flush), whereas fdatasync() skips metadata flushes when i_size and extent maps have not changed (~2x fewer media round-trips on preallocated logs!). O_DIRECT: Bypasses the page cache via Direct Memory Access (DMA) when memory address, byte count, and file offset satisfy statx() STATX_DIOALIGN alignment.

GL-C01 · Linux Systems I/O & Buffering in C439/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

One Layer Down: O_DIRECT 3-Way Modulo Invariant & mmap Page Faults

  • When opening a block-backed file with O_DIRECT (queried dynamically on Linux 6.1+ via `statx(fd, "", AT_E…
GL-C01 · Linux Systems I/O & Buffering in C440/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

One Layer Down: O_DIRECT 3-Way Modulo Invariant & mmap Page Faults

fig_m06_l01_arch.svg

Figure 6.1: Unified VFS page cache, mmap() MAP_SHARED vs MAP_PRIVATE CoW faults, fdatasync()/dir_fd barriers, and 3-way aligned O_DIRECT DMA.

GL-C01 · Linux Systems I/O & Buffering in C441/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

One Layer Down: O_DIRECT 3-Way Modulo Invariant & mmap Page Faults

Query STATX_DIOALIGN for posix_memalign() O_DIRECT buffers, or pre-size WAL segments so i_size stays fixed.

Buffered writes only reach volatile DRAM; power-cut durability requires fdatasync()/fsync() plus fsync(dir_fd) on directory updates.

GL-C01 · Linux Systems I/O & Buffering in C442/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Sync Prototypes, posix_memalign(3) & mmap(2) Reference

  • Define #define _GNU_SOURCE and #define _FILE_OFFSET_BITS 64 before <fcntl.h>, <sys/mman.h>, `<sys/s…
GL-C01 · Linux Systems I/O & Buffering in C443/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

mmap

mmap(2) at a glance — GL-C01
mmap(2)                     GL-C01 Quick Reference                     mmap(2) NAME       mmap, munmap, msync, fdatasync - map page-cache folios and sync media SYNOPSIS       #include <sys/mman.h>       #include <unistd.h>       void *mmap(void *addr, size_t length, int prot, int flags,                  int fd, off_t offset);       int munmap(void *addr, size_t length);       int msync(void *addr, size_t length, int flags);       int fdatasync(int fd); STANDARDS       POSIX.1-2008; O_DIRECT and STATX_DIOALIGN require _GNU_SOURCE on Linux. RETURN VALUE       mmap() returns mapped address, or MAP_FAILED ((void *)-1) on error. Kernel Systems Academy                     m06-l01                     mmap(2) GL-C01 quick reference · full manual page: man 2 mmap 
GL-C01 · Linux Systems I/O & Buffering in C444/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Probing Sync Barriers, mmap CoW vs Shared & STATX_DIOALIGN O_DIRECT

  • Save pagecache_odirect.c below.
GL-C01 · Linux Systems I/O & Buffering in C445/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

pagecache_odirect.c

learner@ksa: ~/gl-c01/m06-l01
learner@ksa:~/gl-c01/m06-l01$ bat pagecache_odirect.c File: pagecache_odirect.c    #define _GNU_SOURCE    #define _FILE_OFFSET_BITS 64    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/mman.h>    #include <sys/resource.h>    #include <sys/stat.h>    #include <unistd.h>        int main(void) {
GL-C01 · Linux Systems I/O & Buffering in C446/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Verifying Durability Barriers, mmap CoW & O_DIRECT Alignment

  • Compile and run pagecache_odirect: verify fdatasync=1, fsync=1, dir_fsync=1, mmap_cow=1, and `odi…
GL-C01 · Linux Systems I/O & Buffering in C447/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Verifying Durability Barriers, mmap CoW & O_DIRECT Alignment

learner@ksa: ~/gl-c01/m06-l01
learner@ksa:~/gl-c01/m06-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror pagecache_odirect.c -o pagecache_odirectlearner@ksa:~/gl-c01/m06-l01./pagecache_odirectlearner@ksa:~/gl-c01/m06-l01test ! -e /tmp/ksa_m06_l01.wal && test ! -e /tmp/ksa_m06_l01_dio.bin && rm -f pagecache_odirectdurability: fdatasync=1 fsync=1 dir_fsync=1 mmap_cow=1odirect: mem_ok=1 aligned_io=1 unaligned_einval=1learner@ksa:~/gl-c01/m06-l01
GL-C01 · Linux Systems I/O & Buffering in C448/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Inside Writeback Flushes, CoW Shadow Pages & Block DMA

  • Notice how pagecache_odirect exposed the unified VFS page cache from three angles: pwrite() dirtied pag…
GL-C01 · Linux Systems I/O & Buffering in C449/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Guided Practice: Preallocated WAL Segment Initializer (fallocate + fdatasync)

  • Why do high-throughput WAL writers pre-size segments (ftruncate or posix_fallocate) once at creation be…
GL-C01 · Linux Systems I/O & Buffering in C450/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Guided Practice: Preallocated WAL Segment Initializer (fallocate + fdatasync)

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C451/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Independent Practice: CLOCK_MONOTONIC Buffered write vs O_DSYNC Latency Distribution

  • Write a C11 benchmark sync_latency.c (-std=c11 -O2 -Wall -Wextra -Werror) on a disk-backed directory (s…
GL-C01 · Linux Systems I/O & Buffering in C452/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: An atomic updater runs write(tfd) -> fsync(tfd) -> close(tfd) -> rename("cfg.tmp", "cfg.json") and still loses the update on a sudden power cut! Root Cause: fsync(tfd) persisted the file's data blocks and inode, but rename() modified the parent directory's dentry in volatile RAM without syncing the directory inode. Fix: Open the parent directory (O_RDONLY | O_DIRECTORY | O_CLOEXEC), call fsync(dir_fd) after rename() (or O_CREAT), and close dir_fd.

GL-C01 · Linux Systems I/O & Buffering in C453/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Warning

warning: Symptom: Adding O_DIRECT to an existing log writer causes write(fd, line, strlen(line)) to fail with EINVAL (or causes open("/tmp/x", O_DIRECT) on tmpfs to fail with EINVAL). Root Cause: O_DIRECT rejects unaligned malloc/stack buffers, non-block-multiple byte counts, unaligned file offsets, and RAM-backed filesystems (tmpfs). Fix: Query STATX_DIOALIGN, allocate posix_memalign() buffers for block-aligned engines, or use buffered writes + fdatasync() for variable-length records.

GL-C01 · Linux Systems I/O & Buffering in C454/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

Why do Write-Ahead Log (WAL) storage engines prefer fdatasync(fd) over fsync(fd) when committing records into a preallocated segment file?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C455/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

Which three values must all be integer multiples of the device's STATX_DIOALIGN alignment boundary when calling pread() or pwrite() on an O_DIRECT descriptor?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C456/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) Suppose you open a file without O_DIRECT and later enable O_DIRECT at runtime via fcntl(). Which fcntl() call sequence is required?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C457/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Quick check

When a process calls mmap(NULL, 4096, PROT_READ | PROT_WRITE, flags, fd, 0) on a file whose 4 KiB folio is already resident in the VFS page cache, how do fault counters and store visibility behave under MAP_SHARED vs MAP_PRIVATE?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C458/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Summary

  • A successful write() only places bytes in the volatile Linux kernel page cache (SIGKILL-safe, not power-fail durable) until an explicit sync barrier completes.
  • fsync(fd) flushes data and all inode metadata, fdatasync(fd) skips non-essential timestamp flushes, O_SYNC/O_DSYNC enforce per-write syncs, and fsync(dir_fd) hardens newly created or renamed directory entries.
  • Demand-paged mmap() faults in VFS page-cache folios on first touch (ru_minflt vs ru_majflt), aliasing dirty folios under MAP_SHARED and cloning Copy-on-Write shadow pages under MAP_PRIVATE.
  • O_DIRECT bypasses the page cache via statx() (STATX_DIOALIGN) + posix_memalign() when buffer address, transfer length, and file offset are aligned, while posix_fadvise(..., POSIX_FADV_DONTNEED) evicts cold sequential cache pages.
GL-C01 · Linux Systems I/O & Buffering in C459/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Summary

  • Next, we connect Ring 3 <stdio.h> buffering (_IOFBF, _IOLBF, _IONBF) directly onto this Ring 0…
GL-C01 · Linux Systems I/O & Buffering in C460/515

GL-C01 · 6.1 (m06-l01)

>_ Kernel Systems Academy

Key takeaways

  • Demand-paged mmap() faults in VFS page-cache folios on first touch (ru_minflt vs ru_majflt), aliasing dirty folios under MAP_SHARED and cloning Copy-on-Write shadow pages under MAP_PRIVATE.
  • O_DIRECT bypasses the page cache via statx() (STATX_DIOALIGN) + posix_memalign() when buffer address, transfer length, and file offset are aligned, while posix_fadvise(..., POSIX_FADV_DONTNEED) evicts cold sequential cache pages.
  • Next, we connect Ring 3 <stdio.h> buffering (_IOFBF, _IOLBF, _IONBF) directly onto this Ring 0 page-cache model to master the two-stage fflush -> fdatasync commit pipeline and fdopen/fileno ownership rules.
GL-C01 · Linux Systems I/O & Buffering in C461/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

stdio Buffering & Descriptor Interop

free preview25 min

What you'll learn

  • Configure _IOFBF, _IOLBF, and _IONBF via setvbuf() and prevent unflushed data loss or duplicate fork() flushes.
  • Execute the two-stage commit barrier (fwrite -> fflush -> fdatasync(fileno(fp)) -> fclose) for durable stdio.
  • Enforce single-owner descriptor lifetime rules when bridging raw descriptors and FILE * streams via fdopen()/fileno().
GL-C01 · Linux Systems I/O & Buffering in C462/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Why fdatasync(fileno(fp)) Alone Syncs Nothing & Double-Close Murders Sockets

  • Two catastrophic bugs occur whenever engineers mix <stdio.h> FILE * streams with raw POSIX descriptors…
GL-C01 · Linux Systems I/O & Buffering in C463/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Why fdatasync(fileno(fp)) Alone Syncs Nothing & Double-Close Murders Sockets

  • Mastering two-layer Linux I/O means tracking bytes across both RAM caches (Ring 3 FILE buffer -> `R…
GL-C01 · Linux Systems I/O & Buffering in C464/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Mental model

note: Two-layer Linux I/O is a two-hop mailroom: fwrite() drops letters into your desk outbox in user space, fflush() carries that outbox down to the kernel loading dock in RAM, and fdatasync() dispatches the delivery truck onto permanent flash media.

Where it stops working: Closing a physical outbox leaves the loading dock doorway open, whereas fclose(fp) closes the underlying kernel file descriptor too — calling close(fd) again closes an unrelated descriptor!

GL-C01 · Linux Systems I/O & Buffering in C465/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

setvbuf() Policies, Two-Stage Durability & fdopen() Ownership

definition: stdio Buffering Policies (_IOFBF, _IOLBF, _IONBF): Configured via setvbuf(fp, buf, mode, size) before the first I/O operation on fp: Full Buffering (_IOFBF) (default when !isatty(fd)—files, pipes, sockets) holds size bytes (4..8 KiB) until full; Line Buffering (_IOLBF) (default on interactive TTYs) flushes on '\n'; Unbuffered (_IONBF) (default on stderr) issues write() per call. Two-Stage Durability Barrier: fwrite() -> fflush(fp) (Ring 3 -> Ring 0 page cache) -> fdatasync(fileno(fp)) (Ring 0 -> NVM media). fdopen(fd, mode) Ownership: Transfers ownership of fd to fp (fclose(fp) closes fd); fileno(fp) borrows _fileno without transferring ownership.

GL-C01 · Linux Systems I/O & Buffering in C466/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

One Layer Down: Two-Zone State Machine & isatty() Mode Selection

  • When glibc first touches stdout (fd 1), _IO_file_doallocate() invokes fstat(1, &st) / isatty(1)…
GL-C01 · Linux Systems I/O & Buffering in C467/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

One Layer Down: Two-Zone State Machine & isatty() Mode Selection

ast_m06_l02_full_arch.svg

Figure 6.2a: Complete two-zone user-space stdio and Linux kernel page cache buffering, flush, and bypass architecture.

GL-C01 · Linux Systems I/O & Buffering in C468/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

One Layer Down: Two-Zone State Machine & isatty() Mode Selection

Stage 1 — fwrite() stages (B, 0, 0) in glibc's Ring 3 heap buffer with zero syscalls (_exit loses it).

Durable stdio commits require Stage 2 fflush(fp) before Stage 3 fdatasync(fileno(fp)), followed by single-owner fclose(fp).

GL-C01 · Linux Systems I/O & Buffering in C469/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

One Layer Down: Two-Zone State Machine & isatty() Mode Selection

fig_m06_l02_arch.svg

Figure 6.2b: Two-stage durability state transitions, setvbuf() policies, and single-owner fdopen() versus borrowed fileno().

GL-C01 · Linux Systems I/O & Buffering in C470/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

setvbuf(3) Lifetime Rule & fdopen(3) Error Handling

  • Include <stdio.h>, <fcntl.h>, <time.h>, and <unistd.h> under #define _POSIX_C_SOURCE 200809L.
GL-C01 · Linux Systems I/O & Buffering in C471/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Probing _IOFBF/_IOLBF/_IONBF, Two-Stage Sync & Ownership Transfer

  • Save stdio_buf_interop.c below.
GL-C01 · Linux Systems I/O & Buffering in C472/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

stdio_buf_interop.c

learner@ksa: ~/gl-c01/m06-l02
learner@ksa:~/gl-c01/m06-l02$ bat stdio_buf_interop.c File: stdio_buf_interop.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <time.h>    #include <unistd.h>        static uint64_t span_ns(struct timespec a, struct timespec b) {        return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL +               (uint64_t)(b.tv_nsec - a.tv_nsec);
GL-C01 · Linux Systems I/O & Buffering in C473/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Verifying Two-Zone Flush Boundaries, Single-Owner Close & Speedup

  • Compile and execute stdio_buf_interop: verify iofbf=0->11, iolbf=5->9, ionbf=3->3, pre_flush=0 ->…
GL-C01 · Linux Systems I/O & Buffering in C474/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Verifying Two-Zone Flush Boundaries, Single-Owner Close & Speedup

learner@ksa: ~/gl-c01/m06-l02
learner@ksa:~/gl-c01/m06-l02gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror stdio_buf_interop.c -o stdio_buf_interoplearner@ksa:~/gl-c01/m06-l02./stdio_buf_interoplearner@ksa:~/gl-c01/m06-l02test ! -e /tmp/ksa_m06_l02.commit && rm -f stdio_buf_interopbuf_modes: iofbf=0->11 iolbf=5->9 ionbf=3->3pipeline_owner: pre_flush=0 post_flush=14 sync=1 raw_ebadf=1 iofbf_faster=1learner@ksa:~/gl-c01/m06-l02
GL-C01 · Linux Systems I/O & Buffering in C475/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Why pre_flush=0 Proves Both Sync Stages Are Mandatory

  • Seeing pre_flush=0 right after fwrite(rec, 1, 14, fp) settles the durability debate permanently: the Li…
GL-C01 · Linux Systems I/O & Buffering in C476/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Guided Practice: Borrowing raw_fd Safely via dup() + fdopen()

  • Suppose a protocol handler receives int client_fd from a caller whose contract states client_fd **must…
GL-C01 · Linux Systems I/O & Buffering in C477/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Guided Practice: Borrowing raw_fd Safely via dup() + fdopen()

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C478/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Independent Practice: Durable Checkpoint Writer Function

  • Write a standalone C11 module durable_save.c (-std=c11 -Wall -Wextra -Werror) implementing `int save_ch…
GL-C01 · Linux Systems I/O & Buffering in C479/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: A helper runs char fastbuf[8192]; setvbuf(fp, fastbuf, _IOFBF, sizeof(fastbuf)); return fp;, causing random stack corruption and SIGSEGV inside main() on later fprintf() or fclose() calls! Root Cause: Non-NULL buf pointers passed to setvbuf() are stored inside fp and written into long after the helper's stack frame returns! Fix: Pass buf = NULL (setvbuf(fp, NULL, _IOFBF, 8192)) so glibc allocates and frees heap storage automatically.

GL-C01 · Linux Systems I/O & Buffering in C480/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Warning

warning: Symptom: Running int fd = open(...); FILE *fp = fdopen(fd, "r"); ... fclose(fp); close(fd); passes single-threaded tests, then randomly disconnects live client sockets under multithreaded load! Root Cause: fclose(fp) already closed fd; when a sibling thread reuses that lowest-numbered descriptor integer, the redundant close(fd) kills the sibling's handle! Fix: Transfer ownership cleanly (fd = -1 after fdopen succeeds); call close(fd) only on the branch where fdopen() returned NULL.

GL-C01 · Linux Systems I/O & Buffering in C481/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

Why does a background daemon whose stdout is redirected to /var/log/daemon.log stop emitting printf("worker ready\n"); lines immediately until 4 KiB or 8 KiB of text accumulates?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C482/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

Which exact call sequence guarantees that records written via fwrite(..., fp) survive a sudden machine power loss before closing fp?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C483/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) If you must wrap raw_fd inside a temporary FILE * stream without allowing fclose(fp) to close raw_fd, which descriptor primitive solves this cleanly?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C484/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Quick check

What happens if a parent process writes "HEADER\n" into a redirected _IOFBF stdout file without calling fflush(stdout) and then calls fork(), after which both parent and child return cleanly from main()?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C485/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Summary

  • glibc FILE streams support _IOFBF (full, default on files/pipes), _IOLBF (line, default on terminals), and _IONBF (unbuffered, default on stderr), configured via setvbuf(fp, NULL, mode, sz) before any I/O.
  • Normal exit() flushes all user-space FILE streams, whereas _exit() traps straight to kernel exit_group() and drops unflushed Ring 3 buffers (and fflush(NULL) must precede fork()).
  • Power-safe stdio durability requires the strict two-stage barrier fwrite() -> fflush(fp) -> fdatasync(fileno(fp)) -> checked fclose(fp).
  • fdopen(fd, mode) transfers descriptor ownership to fp (fclose(fp) closes fd); fileno(fp) borrows _fileno without transferring ownership.
GL-C01 · Linux Systems I/O & Buffering in C486/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Summary

  • Now, in our final capstone lesson (m06-l03), we synthesize every mechanism from Modules 1 through 6 into…
GL-C01 · Linux Systems I/O & Buffering in C487/515

GL-C01 · 6.2 (m06-l02)

>_ Kernel Systems Academy

Key takeaways

  • Power-safe stdio durability requires the strict two-stage barrier fwrite() -> fflush(fp) -> fdatasync(fileno(fp)) -> checked fclose(fp).
  • fdopen(fd, mode) transfers descriptor ownership to fp (fclose(fp) closes fd); fileno(fp) borrows _fileno without transferring ownership.
  • Now, in our final capstone lesson (m06-l03), we synthesize every mechanism from Modules 1 through 6 into a crash-consistent CRC32 + monotonic-epoch Write-Ahead Log (WAL) storage engine!
GL-C01 · Linux Systems I/O & Buffering in C488/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Capstone: Crash-Safe Binary Log

free preview25 minlab lab_m06_durable_wal

What you'll learn

  • Construct self-describing binary Write-Ahead Log frames with magic bytes, 64-bit seq epochs, lengths, and IEEE CRC32.
  • Implement startup crash-recovery scanning that detects torn or corrupt tail frames and heals the log via ftruncate().
  • Serve lock-free latest-key reads via an in-memory offset index and stateless pread() without moving the append cursor.
GL-C01 · Linux Systems I/O & Buffering in C489/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Why In-Place Updates Corrupt State & CRC32 Alone Fails Recycled Logs

  • Imagine an embedded power-controller key-value store that updates "vcore" from "1150mV" (6 bytes) to…
GL-C01 · Linux Systems I/O & Buffering in C490/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Why In-Place Updates Corrupt State & CRC32 Alone Fails Recycled Logs

  • Production storage engines (SQLite WAL, RocksDB, etcd Raft logs) solve both hazards by uniting every…
GL-C01 · Linux Systems I/O & Buffering in C491/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Mental model

note: A crash-safe Write-Ahead Log is like an aircraft flight recorder tape sealed frame-by-frame with sequence numbers and checksum stamps: if power cuts mid-frame, recovery inspectors snip off the broken tail frame cleanly and read any earlier frame by exact byte offset without moving the recording head.

Where it stops working: Snipping physical tape requires hand splicing, whereas ftruncate() updates inode->i_size atomically in the filesystem while leaving concurrent pread() readers completely lock-free at earlier offsets.

GL-C01 · Linux Systems I/O & Buffering in C492/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Write-Ahead Log (WAL), Reflected CRC32 & Monotonic Epoch

definition: Write-Ahead Log (WAL): Originated in the ARIES recovery architecture (Mohan et al.), an append-only binary log where mutations append immutable frames flushed via fdatasync() before acknowledgment, startup recovery truncates uncommitted crash tails via ftruncate(), and point queries read latest committed offsets via stateless pread(). Reflected IEEE 802.3 CRC32 (0xEDB88320U) & Monotonic seq: Processes bits Least-Significant-Bit (LSB)-first over [seq, klen, vlen, key, val] to detect bit-rot and torn writes, while h.seq == expected_seq stops recovery deterministically at recycled-sector boundaries.

GL-C01 · Linux Systems I/O & Buffering in C493/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

One Layer Down: 24-Byte Frame Geometry & Branchless GF(2) CRC32 Math

  • Each WAL record begins with an ABI-locked 24-byte header (struct wal_hdr: `uint32_t magic, crc32, klen,…
GL-C01 · Linux Systems I/O & Buffering in C494/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

One Layer Down: 24-Byte Frame Geometry & Branchless GF(2) CRC32 Math

fig_m06_l03_arch.svg

Figure 6.3: ABI-locked 24-byte CRC32+seq WAL frame layout, recycled-tail ftruncate() crash healing, and lock-free pread() indexing.

GL-C01 · Linux Systems I/O & Buffering in C495/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

One Layer Down: 24-Byte Frame Geometry & Branchless GF(2) CRC32 Math

Seal [seq, klen, vlen, key, val] inside a 24-byte header with branchless CRC32 and commit via write_all() + fdatasync().

Seal immutable WAL frames with branchless CRC32 + monotonic seq, flush via fdatasync(), heal crash tails with ftruncate() + lseek(), and read lock-free via pread().

GL-C01 · Linux Systems I/O & Buffering in C496/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Startup Recovery State Machine & Cursor Resynchronization

  • Walk through the four validation gates executed at byte offset off during startup recovery (exp_seq sta…
GL-C01 · Linux Systems I/O & Buffering in C497/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Building Mini-WAL Commit, Stale-Epoch Guard, Healing & pread Lookup

  • Save mini_wal_demo.c below.
GL-C01 · Linux Systems I/O & Buffering in C498/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

mini_wal_demo.c

learner@ksa: ~/gl-c01/m06-l03
learner@ksa:~/gl-c01/m06-l03$ bat mini_wal_demo.c File: mini_wal_demo.c    #define _FILE_OFFSET_BITS 64    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <string.h>    #include <sys/stat.h>    #include <unistd.h>        #define WAL_MAGIC 0x4B57414CU        struct wal_hdr {        uint32_t magic, crc32, klen, vlen;
GL-C01 · Linux Systems I/O & Buffering in C499/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Verifying Crash-Tail Healing, Stateless pread Lookup & Lab 6

  • Compile and execute mini_wal_demo: verify clean=105, crashed=145, healed=105 (recs=3), and `vcore…
GL-C01 · Linux Systems I/O & Buffering in C500/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Verifying Crash-Tail Healing, Stateless pread Lookup & Lab 6

learner@ksa: ~/gl-c01/m06-l03
learner@ksa:~/gl-c01/m06-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror mini_wal_demo.c -o mini_wal_demolearner@ksa:~/gl-c01/m06-l03./mini_wal_demolearner@ksa:~/gl-c01/m06-l03test ! -e /tmp/ksa_m06_l03.wal && rm -f mini_wal_demowal_recovery: clean=105 crashed=145 healed=105 recs=3wal_lookup: vcore=1200mV writer_fpos=105learner@ksa:~/gl-c01/m06-l03
GL-C01 · Linux Systems I/O & Buffering in C501/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Lab: lab_m06_durable_wal

  • 1.

Verify: ./check.sh exits 0.

GL-C01 · Linux Systems I/O & Buffering in C502/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Full-Course Synthesis & Bridge to GL-C02

  • Trace how every layer in mini_wal_demo reinforced the others: O_CLOEXEC prevented handle leaks, subtrac…
GL-C01 · Linux Systems I/O & Buffering in C503/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Note

note: Later: In Course 2 (GL-C02: linux-c-proc-threads), you will build on these VFS descriptor and durability foundations to master directory trees (opendir/readdir, statx), asynchronous POSIX signals (sigaction, signal masks), multi-process execution (fork, execve, waitpid), and pthread mutex/condvar concurrency!

GL-C01 · Linux Systems I/O & Buffering in C504/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Guided Practice: Adding Tombstone (DELETE) Records to an Append-Only WAL

  • How do append-only WAL engines delete a key like "pll_hz" without erasing or mutating earlier frames in p…
GL-C01 · Linux Systems I/O & Buffering in C505/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Guided Practice: Adding Tombstone (DELETE) Records to an Append-Only WAL

  • 1.
GL-C01 · Linux Systems I/O & Buffering in C506/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Independent Practice: Atomic WAL Log Compaction (compact_wal_at)

  • Over months of updates, an append-only WAL accumulates superseded frames.
GL-C01 · Linux Systems I/O & Buffering in C507/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: Computing a WAL frame's CRC32 over key and val bytes while excluding klen, vlen, and seq lets a corrupted length field shift frame boundaries or trigger gigabyte malloc() calls! Root Cause: Unchecksummed header lengths allow bit-flips in klen/vlen to reinterpret payload bytes as adjacent headers. Fix: Enforce strict upper caps on klen and vlen before reading payloads, and include seq, klen, vlen, key, and val inside the CRC32 envelope.

GL-C01 · Linux Systems I/O & Buffering in C508/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Warning

warning: Symptom: After ftruncate(fd, valid_off) heals a 145-byte crashed WAL back to 105 bytes, the next write() (on a non-O_APPEND handle) injects a 40-byte zero hole at [105..144]! Root Cause: ftruncate() updates inode->i_size to 105 without moving struct file.f_pos down from 145. Fix: Call lseek(fd, valid_off, SEEK_SET) immediately after ftruncate() (or write via O_APPEND / explicit pwrite() offsets).

GL-C01 · Linux Systems I/O & Buffering in C509/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

During startup recovery of an append-only WAL, the scanner verifies 3 intact frames ending at byte 105, followed by 11 bytes of a 4th frame cut short by a power outage. What is the exact recovery action?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C510/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

Why does sequential replay of an append-only WAL from offset 0 to valid_off support key updates ("vcore" changing from "1150mV" to "1200mV") without mutating earlier bytes in place?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C511/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

(Review from earlier lesson) Why can reader threads execute pread(fd, buf, vlen, val_off) concurrently on the WAL descriptor while a writer appends new frames at the tail?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C512/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Quick check

Why do production WAL engines that recycle preallocated log segments pair reflected IEEE 802.3 CRC32 (0xEDB88320U & -(crc & 1U)) with a strictly monotonic 64-bit seq header field?

Select an option or press R to reveal.

GL-C01 · Linux Systems I/O & Buffering in C513/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Summary

  • A crash-safe Write-Ahead Log unites O_CLOEXEC handle hygiene, binary length-prefixed CRC32 framing, fdatasync() + directory fsync() barriers, ftruncate() torn-tail healing, and stateless pread() indexed reads.
  • Reflected IEEE 802.3 CRC32 (0xEDB88320U) processes bits LSB-first using the branchless mask -(crc & 1U) over [seq, klen, vlen, key, val], while monotonic 64-bit seq prevents stale recycled blocks from replaying.
  • Append-only immutable frames replace in-place overwrites with sequential tail appends, enabling lock-free pread() lookups on committed offsets.
  • With Linux file I/O, VFS descriptor tables, stdio codecs, and two-layer durability mastered in GL-C01, you are ready for filesystems, signals, processes, and threads in GL-C02.
GL-C01 · Linux Systems I/O & Buffering in C514/515

GL-C01 · 6.3 (m06-l03)

>_ Kernel Systems Academy

Key takeaways

  • Reflected IEEE 802.3 CRC32 (0xEDB88320U) processes bits LSB-first using the branchless mask -(crc & 1U) over [seq, klen, vlen, key, val], while monotonic 64-bit seq prevents stale recycled blocks from replaying.
  • Append-only immutable frames replace in-place overwrites with sequential tail appends, enabling lock-free pread() lookups on committed offsets.
  • With Linux file I/O, VFS descriptor tables, stdio codecs, and two-layer durability mastered in GL-C01, you are ready for filesystems, signals, processes, and threads in GL-C02.
GL-C01 · Linux Systems I/O & Buffering in C515/515

slides — overview

cover

m01/ Series Orientation, Kernel Boundary & C Toolchain

m02/ Core Unbuffered POSIX File I/O

m03/ Kernel Open-File Internals, Errors & Sparse Files

m04/ File Sharing, Atomic Operations & Descriptor Control

m05/ Standard C Library (stdio) Streams & Formatted I/O

m06/ Two-Layer I/O Buffering, Durability & Capstone Engine

search — fzf

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

keyboard shortcuts — less

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

figure