Shared File Tables & dup Redirection

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.

25 minfree previewLinux 6.12C11glibc 2.39→ module 4 lab
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.

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

Two subtle bugs surface whenever subsystems share files or redirect standard streams. First, two components inside one process each call open("/var/log/audit.bin", O_WRONLY | O_CREAT, 0644) without O_APPEND and alternate 4-byte writes—instead of an 8-byte log, the second component's f_pos = 0 overwrites the first component's bytes in the shared page cache! Second, a daemon helper redirects output to STDOUT_FILENO (1) via dup3(log_fd, STDOUT_FILENO, O_CLOEXEC): it works for months until startup happens to run with descriptor 1 closed so open() allocates log_fd == 1—causing dup3(1, 1, O_CLOEXEC) to fail immediately with EINVAL!

Predicting every multi-descriptor interaction in Linux requires tracing exactly which tier of the three-table VFS hierarchy (files_struct slot vs struct file description vs struct inode) is cloned versus aliased across dual open(), dup/dup2/dup3, and fork().

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.

definition (Dual-Open Independence vs Descriptor Aliasing (dup/dup2/dup3)): 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.

ast_m04_l01_dual_open.svg — Same-process dual open() — fd1 and fd2 allocate…

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

fig_m04_l01_cross_proc.svg — Two independent processes opening the same pathname —…

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

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[], not inside struct file. Consequently, dup(oldfd) and dup2(oldfd, newfd) always clear FD_CLOEXEC (0) on the new slot (so shell redirections like cmd > out.txt survive execve()!), whereas Linux dup3(oldfd, newfd, O_CLOEXEC) sets FD_CLOEXEC (1) atomically on newfd without altering oldfd's bit. Meanwhile, file->f_count tracks total slot references across all processes: file->f_count = sum_over_procs(count(d : p->fdt->fd[d] == file)). Closing oldfd decrements f_count from 2 to 1; VFS invokes f_op->release and frees struct file only when the final alias closes (f_count -> 0).

fig_m04_l01_dup.svg — dup() / dup2() / dup3() — two descriptor slots alias…

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.

Sharing Topologyfiles_struct Slot (FD_CLOEXEC)struct file (f_pos, f_flags, f_count)struct inode & Production Consequence
Dual open() (1 or 2 procs)Separate slot & FD_CLOEXECSeparate struct file (f_pos = 0 each)Shared 1 inode & cacheSilent overwrites unless O_APPEND or pwrite
dup() / dup2()Separate slot (FD_CLOEXEC = 0 on new)Shared 1 struct file (f_count++)Shared 1 inode & cacheLockstep f_pos; dup2(fd, fd) is a safe no-op
dup3(old, new, O_CLOEXEC)Separate slot (FD_CLOEXEC = 1 on new)Shared 1 struct file (f_count++)Shared 1 inode & cacheRejects old == new with -1 (EINVAL)!
fork() (Later: GL-C02)Cloned files_struct tableShared 1 struct file (f_count++)Shared 1 inode & cacheParent & child advance one shared f_pos
step_m04_l01.svg — Only open() allocates a fresh struct file cursor;…step 1/4
  1. Step 1. Flush stdout first and call saved_out = dup(STDOUT_FILENO) to increment the terminal struct file's f_count to 2.
  2. Step 2. Call dup2(log_fd, STDOUT_FILENO) to atomically rebind slot 1 onto log_fd (guarding fd != 1 if using dup3).
  3. Step 3. Emit redirected output and call fflush(stdout) BEFORE restoring slot 1 so _IOFBF bytes land in log_fd.
  4. Step 4. Restore dup2(saved_out, STDOUT_FILENO) and close(saved_out) so terminal f_count returns cleanly to 1.

Figure 4.1d. 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.

fig_m04_l01_arch.svg — Kernel descriptor-to-file-to-inode topologies across…

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

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(). Notice why dup3(fd, fd, O_CLOEXEC) intentionally fails with EINVAL: POSIX forced dup2(fd, fd) to be a no-op, which tragically leaves FD_CLOEXEC unchanged if a caller mistakenly assumed dup2 cleared it; dup3 closed that design flaw by rejecting oldfd == newfd outright. When temporarily redirecting STDOUT_FILENO, always follow the four-step cycle: saved = dup(STDOUT_FILENO) -> fflush(stdout) + dup2(target_fd, STDOUT_FILENO) -> emit output + fflush(stdout) -> dup2(saved, STDOUT_FILENO) + close(saved).

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

Save dual_open_dup.c below. It contrasts dual open() without O_APPEND (8 overwritten bytes "BBBBBBBB") against dual open() with O_APPEND (16 concatenated bytes "AABBAABBAABBAABB"), verifies dup() shared f_pos == 8, tests dup2(fd, fd) no-op vs dup3(fd, fd, O_CLOEXEC) EINVAL, proves per-slot O_CLOEXEC (0/1) via /proc/self/fdinfo/, and executes a full STDOUT_FILENO save-redirect-fflush-restore cycle!

learner@ksa: ~/gl-c01/m04-l01
learner@ksa:~/gl-c01/m04-l01$ bat -H 25 -H 73 -H 86 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;        ssize_t n = read(ifd, buf, sizeof(buf) - 1U);        (void)close(ifd);        if (n <= 0) return 0;        buf[n] = '\0';        const char *f = strstr(buf, "flags:");        unsigned long fl = (f != NULL) ? strtoul(f + 6, NULL, 8) : 0UL;        return ((fl & (unsigned long)O_CLOEXEC) != 0UL) ? 1 : 0;    }        static int run_dual_writes(const char *path, int extra_flags,                             char *out, size_t cap) {        int base = O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | extra_flags;        int fd1 = open(path, base, 0644);        int fd2 = open(path, O_RDWR | O_CLOEXEC | extra_flags);        if (fd1 < 0 || fd2 < 0) return -1;            struct stat s1, s2;        if (fstat(fd1, &s1) < 0 || fstat(fd2, &s2) < 0 ||            s1.st_ino != s2.st_ino) {            (void)close(fd1);            (void)close(fd2);            return -1;        }        for (int i = 0; i < 4; i++) {            if (write(fd1, "AA", 2) != 2 || write(fd2, "BB", 2) != 2) {                (void)close(fd1);                (void)close(fd2);                return -1;            }        }        if (lseek(fd1, 0, SEEK_SET) < 0) return -1;        ssize_t n = read(fd1, out, cap - 1U);        (void)close(fd2);        (void)close(fd1);        (void)unlink(path);        if (n < 0) return -1;        out[n] = '\0';        return (int)n;    }        int main(void) {        char over_buf[32] = {0}, app_buf[32] = {0};        int n_over = run_dual_writes("/tmp/ksa_m04_l01_over.bin", 0,                                     over_buf, sizeof(over_buf));        int n_app = run_dual_writes("/tmp/ksa_m04_l01_app.bin", O_APPEND,                                    app_buf, sizeof(app_buf));        if (n_over < 0 || n_app < 0) return 1;            const char *rpath = "/tmp/ksa_m04_l01_redir.txt";        int fd = open(rpath, O_RDWR | O_CREAT | O_TRUNC, 0644);        if (fd < 0) return 1;            int alias = dup(fd);        if (alias < 0) return 1;        if (write(fd, "KSA-", 4) != 4 || write(alias, "DUP|", 4) != 4) return 1;        off_t shared_pos = lseek(fd, 0, SEEK_CUR);            int same_dup2 = dup2(fd, fd);      errno = 0;        int same_dup3 = dup3(fd, fd, O_CLOEXEC);        int dup3_err = errno;            int clo_fd = dup3(fd, 42, O_CLOEXEC);        if (clo_fd != 42) return 1;        int orig_clo = has_cloexec_fdinfo(fd);        int dup3_clo = has_cloexec_fdinfo(clo_fd);        (void)close(clo_fd);        (void)close(alias);            fflush(stdout);        int saved_out = dup(STDOUT_FILENO);      if (saved_out < 0 || dup2(fd, STDOUT_FILENO) < 0) return 1;        printf("STDOUT_CAPTURED");        fflush(stdout);        if (dup2(saved_out, STDOUT_FILENO) < 0) return 1;        (void)close(saved_out);            char cap_buf[64] = {0};        if (lseek(fd, 0, SEEK_SET) < 0) return 1;        ssize_t cn = read(fd, cap_buf, sizeof(cap_buf) - 1U);        (void)close(fd);        (void)unlink(rpath);        if (cn < 0) return 1;            printf("dual_no_append: bytes=%d payload=%s\n", n_over, over_buf);        printf("dual_o_append:  bytes=%d payload=%s\n", n_app, app_buf);        printf("dup_cursor: shared_f_pos=%lld dup2_self=%s "               "dup3_self_einval=%s cloexec=%d/%d\n",               (long long)shared_pos,               (same_dup2 == fd) ? "noop" : "err",               (same_dup3 == -1 && dup3_err == EINVAL) ? "yes" : "no",               orig_clo, dup3_clo);        printf("redir_restored: captured=%s\n", cap_buf);        return 0;    }
  1. Two open() calls create independent struct file cursors; without O_APPEND, fd2's write at f_pos=0 overwrites fd1's bytes.
  2. dup2(fd, fd) is a POSIX no-op returning fd, whereas Linux dup3(fd, fd, O_CLOEXEC) returns -1 with errno == EINVAL.
  3. Flush stdout BEFORE restoring saved_out onto STDOUT_FILENO so buffered printf bytes land in the capture file, not the terminal.

Verifying Cursor Topologies and Clean Redirection Restore

Compile and execute dual_open_dup: confirm dual_no_append clobbers down to 8 bytes (BBBBBBBB), dual_o_append preserves all 16 bytes, dup advances shared_f_pos=8 with cloexec=0/1, and printf("STDOUT_CAPTURED") lands inside cap_buf before STDOUT_FILENO returns to your terminal!

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_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-l01test ! -e /tmp/ksa_m04_l01_over.bin && test ! -e /tmp/ksa_m04_l01_app.bin && rm -f dual_open_duplearner@ksa:~/gl-c01/m04-l01

Tracing f_count Lifetimes Across Redirection Boundaries

Notice how dup2(fd, STDOUT_FILENO) atomically closed descriptor 1's terminal reference and bound slot 1 onto fd's struct file (f_pos == 8), so printf("STDOUT_CAPTURED") + fflush(stdout) appended 15 bytes at [8..22] (KSA-DUP|STDOUT_CAPTURED)! Rebinding saved_out back onto slot 1 and closing saved_out restored f_count == 1 on the terminal description with zero leaked handles.

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_CLOEXEC guaranteed 1 on dst_fd even when src_fd == dst_fd:

  1. Step 1 (Handle src_fd != dst_fd): Call dup3(src_fd, dst_fd, O_CLOEXEC) (retrying on EINTR), and if it succeeds, call close(src_fd) once and return dst_fd.
  2. Step 2 (Handle src_fd == dst_fd without EINVAL): When src_fd == dst_fd, skip dup3() and call fcntl(dst_fd, F_SETFD, FD_CLOEXEC) (returning -1 if dst_fd is invalid, EBADF) so self-redirection never fails!

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.log 2>&1: save both STDOUT_FILENO and STDERR_FILENO via dup(), bind a scratch log file onto 1 and 2 via dup2(), write interleaved printf() and fprintf(stderr, ...) lines, flush and restore both standard descriptors, and verify in memory that both streams concatenated without overwriting one another (shared struct file!).

Common Production Pitfalls

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.

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.

Knowledge Check

quiz · 1 of 4

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?

quiz · 2 of 4

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?

quiz · 3 of 4

(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?

quiz · 4 of 4

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

Key takeaways

  • 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.
  • 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().
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure