Linux Systems I/O & Buffering in C

For: Embedded Linux, systems, and infrastructure C engineers

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.

18 lessons6 labs~11h 55mLinux 6.12C11glibc 2.39Course 1 of 4 · Foundation

What you'll build

lab m0145 min

Multi-File C11 Static Archive & Syscall Boundary Tracer

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.

learner@ksa: ~/gl-c01/lab-m01
learner@ksa:~/gl-c01/lab-m01./inspector && ./inspector --raw | wc -cframe_bytes=24 payload_bytes=8 null_bytes=2 checksum=0xb6 ebadf_ok=1 glibc=2.3924learner@ksa:~/gl-c01/lab-m01
lab m0245 min

Byte-Exact Framed Slice Copier

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.

learner@ksa: ~/gl-c01/lab-m02
learner@ksa:~/gl-c01/lab-m02./framed_copy sample.bin slice.bin 16 24 && stat -c 'bytes=%s mode=%a' slice.bin && cat slice.bin && echocopied=24bytes=24 mode=644KSA_SLICE_PAYLOAD_24BYTElearner@ksa:~/gl-c01/lab-m02
lab m0350 min

Sparse Partition Image Builder & Hole Inspector

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.

learner@ksa: ~/gl-c01/lab-m03
learner@ksa:~/gl-c01/lab-m03./sparse_img part.img && ./sparse_img part.img --append-tag AUDIT_01logical_size=4194304 phys_bytes=8192 hole_zero_ok=1 superblock_ok=1 append_eof_ok=1logical_size=4194312 phys_bytes=12288 hole_zero_ok=1 superblock_ok=1 append_eof_ok=1learner@ksa:~/gl-c01/lab-m03
lab m0445 min

Race-Free Positional Record Store

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.

learner@ksa: ~/gl-c01/lab-m04
learner@ksa:~/gl-c01/lab-m04./atomic_kv init store.db 6 && ./atomic_kv put store.db 4 psu.vout 12100mV && ./atomic_kv get store.db 4INIT slots=6 bytes=384PUT slot=4 f_pos=0GET slot=4 key=psu.vout val=12100mV f_pos=0learner@ksa:~/gl-c01/lab-m04
lab m0545 min

Bounded stdio Sensor Log Parser & Binary Codec

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.

learner@ksa: ~/gl-c01/lab-m05
learner@ksa:~/gl-c01/lab-m05./telemetry_codec encode sensors.csv sensors.bin && ./telemetry_codec inspect sensors.bin 64ENCODE valid=4 rejected=0 bytes=96VALID=4 MIN_MV=-120 MAX_MV=12050 EOF_CLEAN=1learner@ksa:~/gl-c01/lab-m05
lab m0690 min

Crash-Consistent CRC32 Write-Ahead Log & KV 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.

learner@ksa: ~/gl-c01/lab-m06
learner@ksa:~/gl-c01/lab-m06./durable_wal append engine.wal boot.mode primary && ./durable_wal append engine.wal boot.mode fallback && ./durable_wal get engine.wal boot.modeCOMMIT key=boot.mode bytes=32COMMIT key=boot.mode bytes=33VALUE fallback f_pos=0learner@ksa:~/gl-c01/lab-m06

Syllabus

gl-c01/

  • m01/ 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.

    • Porting bare-metal firmware habits into a hosted Linux C daemon triggers immediate segmentation faults or burns microseconds in avoidable CPU privilege switches. In this opening lesson of GL-C01, you will map the hardware privilege boundary, trace how system calls and the vDSO bridge Ring 3 and Ring 0, and benchmark a strict ISO C11 probe.

    • Signed integer overflow checks silently deleted at -O2, strlen() truncating binary frames at 0x00, unsigned size_t wraparound on -1 errors, and decimal 644 permission literals cause catastrophic C bugs. You will master the four-stage GCC/ar pipeline, feature-test macros, POSIX boundary types, and ISO C11 Undefined Behavior defenses.

    • Confusing pure Ring 3 library helpers with Ring 0 syscall wrappers—or misreading execve ENOENT missing-loader errors and stale errno values—paralyzes production debugging. You will trace ELF PT_INTERP and CRT _start startup, inspect .plt/.got.plt dynamic relocations, test thread-local errno, and verify exact syscall counts under strace.

  • m02/ 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.

    • Omitting O_CLOEXEC leaks sensitive descriptors across execve(), testing (flags & O_RDONLY) evaluates false on every file, and forgetting the variadic mode argument on O_CREAT stamps random stack bits onto disk. You will master lowest-slot descriptor allocation, open() flag bitmasks, 16-bit mode_t permissions, and UB-free unsigned bit shifts.

    • Unlooped read() and write() calls drop tail bytes on pipes, signals, and >2 GiB files, passing raw read() buffers to printf("%s") leaks stack memory, and retrying close() on EINTR kills sibling threads' sockets. You will implement binary-safe write_all() and read_full() loops and enforce Linux close() contracts.

    • Reading right after writing on an O_RDWR descriptor returns zero bytes unless you understand the shared kernel offset f_pos, while opening an O_TRUNC output file before validating input slice bounds destroys existing data on failure. You will master 64-bit lseek(), SEEK_DATA/SEEK_HOLE, signed off_t overflow guards, and all five POSIX slicing patterns.

  • m03/ 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.

    • Confusing directory filenames with on-disk inodes—or confusing per-process descriptors with kernel struct file descriptions—makes unlinked 10 GiB disk leaks, hard links, and shared cursors impossible to diagnose. You will map ext4 disk geometry into the three-tier VFS RAM hierarchy, trace CONTAINER_OF dispatch, and inspect /proc/self/fdinfo live.

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

    • Pre-filling multi-gigabyte partition images with literal zero writes wears out flash media and exhausts disk blocks, while calling lseek(fd, 0, SEEK_SET) before write() on an O_APPEND descriptor fails silently to update byte 0. You will build sparse hole files, compare st_size against st_blocks * 512, and prove O_TRUNC and O_APPEND semantics.

  • m04/ 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.

    • Opening the same file twice in one process creates silent cursor-overwrite bugs, whereas duplicating a descriptor aliases one shared f_pos across handles and trips dup3() self-duplication EINVAL traps. You will compare all three VFS sharing topologies, test dup/dup2/dup3 flags, and implement leak-free STDOUT_FILENO redirection.

    • Splitting an existence check or cursor seek across two syscalls opens a preemption window where attackers swap symlinks or sibling threads clobber record offsets. You will eliminate TOCTOU and cursor races using O_CREAT | O_EXCL, directory-pinned openat(), kernel-locked O_APPEND, and stateless pread()/pwrite().

    • Calling fcntl(fd, F_SETFL, O_NONBLOCK) without F_GETFL silently wipes O_APPEND, unpadded long fields inside custom ioctl structs break 32/64-bit ABIs with ENOTTY, and shrinking a file with ftruncate() leaves f_pos stranded past EOF. You will master fcntl flag tiers, ABI-safe _IOWR ioctls, and ftruncate() resizing.

  • m05/ 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.

    • Emitting thousands of tiny telemetry records via raw write() syscalls burns microseconds in Ring 3-to-Ring 0 trap overhead, while naive fopen("w+") omits O_CLOEXEC and O_EXCL protections. You will dissect glibc FILE control blocks, benchmark buffered syscall amortization, map fopen() modes to openat() flags, and test open_memstream().

    • Looping on while (!feof(fp)) duplicates the final record on every clean file, storing fgetc() into char spins forever on unsigned-char ARMv7 Linux, and skipping fseeko() between fwrite() and fread() corrupts update streams. You will master item-counted binary stdio, 64-bit fseeko/ftello, turnaround barriers, and 257-state EOF triage.

    • Unchecked pos += snprintf(buf + pos, cap - pos, ...) loops wrap unsigned capacities into massive heap overruns on truncation, while fscanf("%s") overflows buffers and wedges streams on malformed lines. You will master portable <inttypes.h> formatting, deterministic snprintf() truncation math, and line-isolated fgets() + strtol() parsers.

  • m06/ 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.

    • A successful write() only copies bytes into volatile kernel DRAM—an abrupt power cut erases committed transactions unless explicit persistence barriers flush both file data and parent directories. You will master fsync(), fdatasync(), directory syncs, demand-paged mmap() CoW vs shared faults, and STATX_DIOALIGN O_DIRECT DMA.

    • Calling fdatasync(fileno(fp)) without fflush(fp) first syncs an empty kernel page cache while committed bytes sit stranded in Ring 3 heap RAM, and calling close(fd) after fclose(fdopen(fd, ...)) kills unrelated sockets! You will master setvbuf() modes, two-stage durability, and single-owner fdopen()/fileno() rules.

    • In-place record overwrites corrupt both old and new values on power loss, while CRC32-only WAL headers replay stale transactions when preallocated log segments are recycled. In this capstone lesson you will synthesize O_CLOEXEC, branchless IEEE 802.3 CRC32 + 64-bit seq WAL framing, fdatasync(), ftruncate() crash healing, and lock-free pread() indexing.

Prerequisites

  • requiredWorking C11 syntax: pointers, arrays, structs, fixed-width integers, and header files
  • requiredBasic Linux terminal familiarity: directory navigation and editing source files
  • Bridged in M1Bare-metal MCU firmware vs Linux kernel driver vs user-space process boundary (Module 1, Lesson 1)
  • Bridged in M1GCC 4-stage pipeline (-E, -S, -c, ld), static/shared libraries, and Makefile rules (Module 1, Lesson 2)
  • Bridged in M1Navigating Linux manual sections (man 1/2/3) & _POSIX_C_SOURCE / _GNU_SOURCE macros (Module 1, Lesson 2)
  • Bridged in M1Systems C integer contracts (size_t vs ssize_t, off_t, mode_t), octal 0644, and errno/strace (Module 1, Lessons 2–3)

Series map

  1. GL-C01Syscalls, File Tables & Buffering — Kernel boundary, glibc, GCC/Make, POSIX file I/O, VFS open-file tables, atomic I/O, stdio & durability this course
  2. GL-C02Filesystems, Signals, Processes & Threads — stat/inodes, directory traversal, system info/time, POSIX signals, fork/exec/wait, daemons & pthreads
  3. GL-C03Advanced I/O, IPC & Network Sockets — Nonblocking I/O, poll/epoll, mmap, record locks, pipes/FIFOs/SysV IPC & TCP/UDP socket servers
  4. GL-C04Embedded Linux Peripherals, Display, Video & Audio — Sysfs GPIO/LED/PWM, evdev input, RTC/I2C/SPI/UART, Framebuffer/DRM, V4L2 camera & ALSA audio

Related live cohorts: KRN-101 · Linux Systems & Kernel Foundations (live cohort) EMB-100 · Embedded Linux: Toolchain to Product (live cohort)

Companion formats

Slide deck

16:9 review slides with terminal listings, diagrams, and speaker notes.

Reference handbook

Printable HTML and PDF engineering reference covering every module and UAPI.

Flashcards

Leitner spaced-repetition terminal cards and TSV deck for syscalls, flags, and pitfalls.

Kernel Systems Academy engineering studio

Every Kernel Systems Academy course follows our 35% principles / 20% guided investigation / 45% engineering studio pedagogy. Listings are compiled against Linux 6.12 · C11 · glibc 2.39 under strict compiler flags (-Wall -Wextra -Werror), and each module culminates in an evidence-checked lab graded locally by ./check.sh.

Frequently asked questions

Can I study this course offline from disk?

Yes. All fonts, stylesheets, diagrams, search indexes, and progress trackers use relative paths and local browser storage, so the bundle works identically over HTTP and file://.

How are the hands-on labs graded?

Each lab directory includes starter source files and an executable ./check.sh runner emitting TAP version 13 diagnostics (ok / not ok) and exiting 0 when every check passes.

What is included in the free preview?

Preview lessons and the opening module lab are unlocked in full so you can inspect our C11 listings, strace transcripts, and ./check.sh workflow before subscribing.

search — fzf

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

keyboard shortcuts — less

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

figure