stdio Buffering & Descriptor Interop
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.
What you'll learn
- Configure
_IOFBF,_IOLBF, and_IONBFviasetvbuf()and prevent unflushed data loss or duplicatefork()flushes. - Execute the two-stage commit barrier (
fwrite->fflush->fdatasync(fileno(fp))->fclose) for durablestdio. - Enforce single-owner descriptor lifetime rules when bridging raw descriptors and
FILE *streams viafdopen()/fileno().
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 without mapping both buffering zones. First, a configuration writer runs fwrite(&commit_rec, sizeof(commit_rec), 1, fp); fdatasync(fileno(fp)); and acknowledges commit—yet on power loss the file is 0 bytes long! Why? Because fwrite() copied commit_rec into fp's Ring 3 _IOFBF heap buffer (0 syscalls), so fdatasync(fileno(fp)) flushed an empty kernel page cache! Second, a network service wraps a socket or file via FILE *fp = fdopen(fd, "r");, later calls fclose(fp);, and "for completeness" also calls close(fd);—silently closing a brand-new connection opened on another thread that just reused slot fd!
Mastering two-layer Linux I/O means tracking bytes across both RAM caches (Ring 3 FILE buffer -> Ring 0 VFS page cache -> non-volatile media) and enforcing strict single-owner lifetime rules across fdopen() and fileno().
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!
definition (setvbuf() Policies, Two-Stage Durability & fdopen() Ownership): 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.
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): if S_ISCHR(st.st_mode) on a terminal, stdout selects _IOLBF so printf("booting...\n") appears immediately; if redirected to /var/log/daemon.log or a systemd pipe, stdout switches silently to 4,096- or 8,192-byte _IOFBF, delaying log lines until thousands of bytes accumulate (and duplicating any unflushed buffer bytes across both parent and child if fork() runs before fflush(NULL)!). Tracing byte residence (B_user, B_pagecache, B_media) across our four-step commit pipeline makes every failure mode transparent: (B, 0, 0) --[fflush(fp)]--> (0, B_dirty, 0) --[fdatasync(fileno(fp))]--> (0, B_clean, B). Skipping fflush(fp) leaves (B, 0, 0) during fdatasync(); skipping fdatasync() leaves (0, B_dirty, 0), which survives SIGKILL yet vanishes on power cut!
| Buffering / Interop Primitive | Default Target | Kernel Syscall & Lifetime Contract |
|---|---|---|
setvbuf(fp, NULL, _IOFBF, sz) | Regular files, pipes, sockets | Heap-allocates sz bytes; flushes when full, fflush, fclose, exit |
setvbuf(fp, NULL, _IOLBF, sz) | Interactive TTY (stdin/stdout) | Flushes immediately on '\n' (systemd services often set _IOLBF) |
setvbuf(fp, NULL, _IONBF, 0) | stderr (fd 2) | Every fwrite/fputs traps via write() immediately |
fflush(fp) / fflush(NULL) | fp / all open output streams | Drains Ring 3 buffer into Ring 0 page cache (0 ok, EOF err) |
fileno(fp) | Borrows int fd from fp | Safe for fdatasync(fileno(fp)) or fstat; never close(fileno(fp)) |
fdopen(fd, mode) | Wraps open fd in FILE * | mode must match O_ACCMODE (never truncates!); fclose(fp) closes fd |
Figure 6.2a. Complete two-zone user-space stdio and Linux kernel page cache buffering, flush, and bypass architecture.
- Step 1. Stage 1 — fwrite() stages (B, 0, 0) in glibc's Ring 3 heap buffer with zero syscalls (_exit loses it).
- Step 2. Stage 2 — fflush(fp) drains the Ring 3 FILE buffer via write() into the Ring 0 kernel page cache.
- Step 3. Stage 3 — fdatasync(fileno(fp)) flushes dirty kernel RAM folios onto non-volatile NVMe/flash media.
- Step 4. Stage 4 — fclose(fp) frees the FILE struct and closes _fileno once; never call close(raw_fd) again.
Figure 6.2b. Durable stdio commits require Stage 2 fflush(fp) before Stage 3 fdatasync(fileno(fp)), followed by single-owner fclose(fp).
Figure 6.2b. Two-stage durability state transitions, setvbuf() policies, and single-owner fdopen() versus borrowed fileno().
setvbuf(3) Lifetime Rule & fdopen(3) Error Handling
Include <stdio.h>, <fcntl.h>, <time.h>, and <unistd.h> under #define _POSIX_C_SOURCE 200809L. Always pass buf = NULL to setvbuf(fp, NULL, _IOFBF, 8192) unless your custom buffer has static or heap lifetime outliving fclose(fp)—passing a local stack array inside a helper function causes use-after-return stack corruption! Also note fdopen(fd, mode)'s failure branch: if fdopen() returns NULL (for example, EINVAL because fd was O_RDONLY and mode was "w"), fd was not consumed and you must still close(fd); once fdopen() returns non-NULL, fp owns fd exclusively.
Probing _IOFBF/_IOLBF/_IONBF, Two-Stage Sync & Ownership Transfer
Save stdio_buf_interop.c below. First, probe_buf_mode() duplicates a scratch fd (dup(fd) so fd survives fclose(fp)!), configures setvbuf(), writes text, and inspects live kernel i_size via lseek(fd, 0, SEEK_END) before and after fclose(fp)—proving _IOFBF withholds "HELLO_NO_NL" (0 -> 11), _IOLBF flushes "LINE\n" (5) on newline while holding "TAIL" (5 -> 9), and _IONBF writes "NOW" immediately (3 -> 3). Second, main() executes the two-stage commit barrier (pre_flush=0, post_flush=14, sync=1), proves fcntl(raw_fd, F_GETFD) returns -1 (EBADF) after fclose(fp), and times 1,024 _IONBF vs _IOFBF fwrite() calls via CLOCK_MONOTONIC!
learner@ksa:~/gl-c01/m06-l02$ bat -H 17 -H 64 -H 71 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); } static int probe_buf_mode(int mode, const char *msg, off_t *pre_out, off_t *post_out) { const char *tmp = "/tmp/ksa_m06_mode.tmp"; (void)unlink(tmp); int fd = open(tmp, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) return -1; int dup_fd = dup(fd); if (dup_fd < 0) { (void)close(fd); return -1; } FILE *fp = fdopen(dup_fd, "w"); if (!fp || setvbuf(fp, NULL, mode, 4096U) != 0) { if (fp) (void)fclose(fp); else (void)close(dup_fd); (void)close(fd); return -1; } if (fputs(msg, fp) < 0) { (void)fclose(fp); (void)close(fd); return -1; } *pre_out = lseek(fd, 0, SEEK_END); if (fclose(fp) != 0) { (void)close(fd); return -1; } *post_out = lseek(fd, 0, SEEK_END); (void)close(fd); (void)unlink(tmp); return 0; } int main(void) { off_t iofbf_pre = -1, iofbf_post = -1; off_t iolbf_pre = -1, iolbf_post = -1; off_t ionbf_pre = -1, ionbf_post = -1; if (probe_buf_mode(_IOFBF, "HELLO_NO_NL", &iofbf_pre, &iofbf_post) < 0 || probe_buf_mode(_IOLBF, "LINE\nTAIL", &iolbf_pre, &iolbf_post) < 0 || probe_buf_mode(_IONBF, "NOW", &ionbf_pre, &ionbf_post) < 0) { return 1; } printf("buf_modes: iofbf=%lld->%lld iolbf=%lld->%lld ionbf=%lld->%lld\n", (long long)iofbf_pre, (long long)iofbf_post, (long long)iolbf_pre, (long long)iolbf_post, (long long)ionbf_pre, (long long)ionbf_post); const char *path = "/tmp/ksa_m06_l02.commit"; int raw_fd = open(path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (raw_fd < 0) return 1; FILE *fp = fdopen(raw_fd, "w+"); if (!fp || setvbuf(fp, NULL, _IOFBF, 4096U) != 0) return 1; const char *rec = "COMMIT_SEQ=42\n"; if (fwrite(rec, 1U, 14U, fp) != 14U) return 1; off_t size_before_flush = lseek(raw_fd, 0, SEEK_END); if (fflush(fp) != 0) return 1; off_t size_after_flush = lseek(raw_fd, 0, SEEK_END); int sync_ok = (fdatasync(fileno(fp)) == 0) ? 1 : 0; if (fclose(fp) != 0) return 1; errno = 0; int fd_check = fcntl(raw_fd, F_GETFD); int closed_ebadf = (fd_check == -1 && errno == EBADF) ? 1 : 0; struct timespec t0, t1, t2; FILE *ufp = fopen(path, "we"); if (!ufp || setvbuf(ufp, NULL, _IONBF, 0U) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t0); for (int i = 0; i < 1024; i++) { if (fwrite("ABCD", 1U, 4U, ufp) != 4U) return 1; } if (fclose(ufp) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t1); FILE *bfp = fopen(path, "we"); if (!bfp || setvbuf(bfp, NULL, _IOFBF, 8192U) != 0) return 1; for (int i = 0; i < 1024; i++) { if (fwrite("ABCD", 1U, 4U, bfp) != 4U) return 1; } if (fclose(bfp) != 0) return 1; clock_gettime(CLOCK_MONOTONIC, &t2); (void)unlink(path); int iofbf_faster = (span_ns(t0, t1) > span_ns(t1, t2)) ? 1 : 0; printf("pipeline_owner: pre_flush=%lld post_flush=%lld sync=%d " "raw_ebadf=%d iofbf_faster=%d\n", (long long)size_before_flush, (long long)size_after_flush, sync_ok, closed_ebadf, iofbf_faster); return 0; }- dup(fd) increments struct file.f_count to 2 so fclose(fp) closes dup_fd while keeping fd open to measure kernel i_size.
- Before fflush(fp), all 14 bytes sit in Ring 3 heap RAM (size_before_flush == 0); fflush() pushes them to the page cache before fdatasync().
- fclose(fp) closed raw_fd via single-owner transfer, so fcntl(raw_fd, F_GETFD) returns -1 with errno == EBADF.
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 -> post_flush=14, raw_ebadf=1, and iofbf_faster=1 (8 KiB _IOFBF outperforming 1,024 unbuffered _IONBF traps!).
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_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-l02test ! -e /tmp/ksa_m06_l02.commit && rm -f stdio_buf_interoplearner@ksa:~/gl-c01/m06-l02Why 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 Linux kernel VFS inode literally knew nothing about those 14 bytes until fflush(fp) issued write() (post_flush=14), after which fdatasync(fileno(fp)) committed the dirty page-cache folio onto media and fclose(fp) closed raw_fd cleanly (raw_ebadf=1).
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 remain open after your helper parses one text header line via fgets():
- Step 1 (Clone the descriptor with
O_CLOEXEC): Callint tmp_fd = fcntl(client_fd, F_DUPFD_CLOEXEC, 0);and return-1iftmp_fd < 0. - Step 2 (Check the
fdopenerror branch): CallFILE *fp = fdopen(tmp_fd, "r");—if!fp, callclose(tmp_fd)before returning-1; iffpsucceeds, watch out for_IOFBFread-ahead consuming payload bytes past the header line (use_IONBFonfpif binary bytes follow onclient_fd!), and letfclose(fp)closetmp_fdwhileclient_fdstays valid!
Independent Practice: Durable Checkpoint Writer Function
Write a standalone C11 module durable_save.c (-std=c11 -Wall -Wextra -Werror) implementing int save_checkpoint_at(int dfd, const char *final_name, const struct ckpt *c) that combines directory-pinned openat(dfd, "ckpt.tmp", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600), fdopen(tfd, "w"), setvbuf(fp, NULL, _IOFBF, 4096), formatted header + binary payload fwrite(), the strict two-stage barrier (fflush(fp) -> fdatasync(fileno(fp)) -> checked fclose(fp)), renameat(), and fsync(dfd).
Common Production Pitfalls
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.
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.
Knowledge Check
Key takeaways
glibcFILEstreams support_IOFBF(full, default on files/pipes),_IOLBF(line, default on terminals), and_IONBF(unbuffered, default onstderr), configured viasetvbuf(fp, NULL, mode, sz)before any I/O.- Normal
exit()flushes all user-spaceFILEstreams, whereas_exit()traps straight to kernelexit_group()and drops unflushedRing 3buffers (andfflush(NULL)must precedefork()). - Power-safe
stdiodurability requires the strict two-stage barrierfwrite()->fflush(fp)->fdatasync(fileno(fp))-> checkedfclose(fp). fdopen(fd, mode)transfers descriptor ownership tofp(fclose(fp)closesfd);fileno(fp)borrows_filenowithout transferring ownership.- Now, in our final capstone lesson (
m06-l03), we synthesize every mechanism from Modules 1 through 6 into a crash-consistentCRC32+ monotonic-epoch Write-Ahead Log (WAL) storage engine!