File Offsets & lseek Slicing

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.

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

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-access binary records. First, a developer opens a scratch file with O_RDWR | O_CREAT | O_TRUNC, writes a 512-byte calibration table, immediately calls read_full(fd, verify_buf, 512) to verify it, and gets 0 bytes (EOF)—because a single descriptor maintains one shared kernel offset (f_pos), now parked at byte 512! Second, a slice-extraction CLI opens dst_path with O_WRONLY | O_CREAT | O_TRUNC at line 1 of copy_slice() and then checks lseek(src_fd, 0, SEEK_END): when a user accidentally pipes stdin (ESPIPE) or requests an out-of-range offset, the tool aborts with an error message after wiping the existing destination file to 0 bytes!

Random-access I/O requires three engineering habits: explicit cursor positioning via 64-bit lseek(), overflow-safe signed off_t arithmetic, and strict precondition validation on source descriptors before mutating or truncating any destination pathname.

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.

definition (Shared File Offset (f_pos), lseek() & Extent Seeks): 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.

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 mutex serializing concurrent lseek/read/write updates on shared handles), dispatches file->f_op->llseek, validates that the computed target coordinate is non-negative (>= 0, returning -EINVAL otherwise) and does not exceed sb->s_maxbytes (-EINVAL / -EOVERFLOW), writes file->f_pos, and returns the new off_t position—performing zero block I/O. Pipes, FIFOs, and sockets lack a seekable .llseek handler (noop_llseek / no_llseek) and reject lseek() immediately with -ESPIPE.

Because off_t is signed ([-2^63, 2^63 - 1] under _FILE_OFFSET_BITS=64 so negative SEEK_CUR deltas and (off_t)-1 error sentinels work), adding an untrusted positive length to offset directly (offset + length > file_size) risks signed 64-bit overflow Undefined Behavior! Always rearrange slice-bound validation as subtraction after checking non-negativity: 0 <= offset && offset <= file_size && length <= (size_t)(file_size - offset). That single subtraction formula is 100% immune to signed overflow across the entire 64-bit off_t range.

Pattern / whence ModeSyscall IdiomKernel Offset / Return Contract
SEEK_SET / SEEK_CUR / SEEK_ENDlseek(fd, off, whence)Sets 0 + off, f_pos + off (0 queries cursor), or i_size + off
SEEK_DATA / SEEK_HOLElseek(fd, off, SEEK_DATA)Returns next allocated byte >= off or hole >= off (ENXIO past EOF)
1. Existing-file probe`open(p, O_RDONLY \O_CLOEXEC)`Verifies p exists (ENOENT if absent) with zero mutation
2 & 3. Clean vs exclusive createO_CREAT vs `O_CREAT \O_EXCL`O_EXCL fails atomically with EEXIST if p already exists
4. Destructive replace`O_WRONLY \O_CREAT \O_TRUNC`Resets i_size = 0 on open so stale trailing bytes never survive
5. Side-effect-safe slice [N, N+L)SEEK_END check -> SEEK_SET(N) -> open(dst)Validates seekability (ESPIPE) & bounds before touching dst
fig_m02_l03_arch.svg — Positioning struct file.f_pos with lseek(), guarding…

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.

step_m02_l03.svg — Validate source seekability and subtraction bounds via…step 1/4
  1. Step 1. Probe source size with lseek(sfd, 0, SEEK_END) first so pipes/sockets fail fast with ESPIPE before touching dst.
  2. Step 2. Validate 0 <= off <= src_sz && len <= (size_t)(src_sz - off) via subtraction to avoid signed off_t overflow UB.
  3. Step 3. Seek sfd to req_off via SEEK_SET and read_full() the window, advancing shared f_pos cleanly.
  4. Step 4. Open dst with O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC and commit the verified slice via write_all().

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

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_HOLE) above <sys/types.h>, <fcntl.h>, and <unistd.h>. On 64-bit x86-64 (LP64), off_t is natively 64-bit, whereas on 32-bit ARMv7 (ILP32), omitting _FILE_OFFSET_BITS 64 leaves off_t as a 32-bit signed long (2 GiB - 1 limit, failing with EOVERFLOW on larger images) and routes to legacy lseek instead of _llseek.

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.              EOVERFLOW Resulting file offset cannot be represented in off_t.        ESPIPE fd refers to a pipe, FIFO, or socket (non-seekable stream). NOTES       lseek(fd, 0, SEEK_CUR) queries the active offset without moving f_pos. SEE ALSO       dup(2), ftruncate(2), open(2), pread(2), read(2), write(2) Kernel Systems Academy                   Lesson 2.3                   lseek(2) GL-C01 quick reference · full manual page: man 2 lseek 

Implementing All Five Canonical Patterns & Extent Seeks in C11

Save offset_patterns.c below. It verifies UB-free safe_add_off() overflow guards, executes all five canonical patterns (ENOENT probe, O_CREAT | O_EXCL 2,048-byte creation + EEXIST guard, SEEK_END + SEEK_DATA/SEEK_HOLE extent probes + negative EINVAL check, pre-validated [500..1524) slice extraction into an O_TRUNC target), and confirms ESPIPE when STDIN_FILENO is a pipe!

learner@ksa: ~/gl-c01/m02-l03
learner@ksa:~/gl-c01/m02-l03$ bat -H 14 -H 91 -H 106 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) {            return -1;        }        if (delta < 0 && cur < 0 - delta) {            return -1;        }        *out = cur + delta;        return 0;    }        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) {            ssize_t n = write(fd, p, left);            if (n < 0) {                if (errno == EINTR) continue;                return -1;            }            p += (size_t)n;            left -= (size_t)n;        }        return 0;    }        static ssize_t read_full(int fd, void *buf, size_t count) {        uint8_t *p = (uint8_t *)buf;        size_t total = 0U;        while (total < count) {            ssize_t n = read(fd, p + total, count - total);            if (n == 0) break;            if (n < 0) {                if (errno == EINTR) continue;                return -1;            }            total += (size_t)n;        }        return (ssize_t)total;    }        int main(void) {        const char *src = "/tmp/ksa_pat_src.bin";        const char *dst = "/tmp/ksa_pat_dst.bin";        (void)unlink(src);        (void)unlink(dst);            off_t guarded = 0;        int ovf_caught = (safe_add_off((off_t)INT64_MAX - 10, 32, &guarded) == -1);            errno = 0;        int missing_fd = open(src, O_RDONLY | O_CLOEXEC);        int p1_enoent = (missing_fd == -1 && errno == ENOENT);            int sfd = open(src, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC,                       S_IRWXU | S_IRGRP | S_IROTH);        if (sfd == -1) return EXIT_FAILURE;            uint8_t zeros[1024], ones[1024];        memset(zeros, 0x00U, sizeof(zeros));        memset(ones, 0xFFU, sizeof(ones));        if (write_all(sfd, zeros, sizeof(zeros)) == -1 ||            write_all(sfd, ones, sizeof(ones)) == -1) {            return EXIT_FAILURE;        }            errno = 0;        int dup_fd = open(src, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);        int p3_eexist = (dup_fd == -1 && errno == EEXIST);            off_t src_sz = lseek(sfd, 0, SEEK_END);        off_t d0 = lseek(sfd, 0, SEEK_DATA);        off_t h0 = lseek(sfd, 0, SEEK_HOLE);        int extent_ok = (d0 == 0 && h0 == src_sz);            errno = 0;        off_t neg_rc = lseek(sfd, -5000, SEEK_END);        int neg_einval = (neg_rc == (off_t)-1 && errno == EINVAL);          off_t req_off = 500;        size_t req_len = 1024U;        if (src_sz < 0 || req_off > src_sz ||            req_len > (size_t)(src_sz - req_off) ||            lseek(sfd, req_off, SEEK_SET) == (off_t)-1) {            return EXIT_FAILURE;        }        uint8_t slice[1024];        ssize_t got = read_full(sfd, slice, req_len);        off_t cur_after = lseek(sfd, 0, SEEK_CUR);            int dfd = open(dst, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,                       S_IRWXU | S_IRGRP | S_IROTH);        if (dfd == -1 || write_all(dfd, slice, (size_t)got) == -1) {          return EXIT_FAILURE;        }        off_t dst_sz = lseek(dfd, 0, SEEK_END);            errno = 0;        off_t pipe_rc = lseek(STDIN_FILENO, 0, SEEK_CUR);        int pipe_espipe = (pipe_rc == (off_t)-1 && errno == ESPIPE);            (void)close(dfd);        (void)close(sfd);        (void)unlink(src);        (void)unlink(dst);            printf("p1_enoent=%d p3_eexist=%d src_size=%lld dst_size=%lld\n",               p1_enoent, p3_eexist, (long long)src_sz, (long long)dst_sz);        printf("cur_after=%lld boundary=0x%02x,0x%02x ovf=%d ext=%d err=%d,%d\n",               (long long)cur_after, slice[523], slice[524],               ovf_caught, extent_ok, neg_einval, pipe_espipe);        return EXIT_SUCCESS;    }
  1. Test cur > INT64_MAX - delta before addition so untrusted 64-bit offsets never trigger signed overflow UB.
  2. SEEK_DATA and SEEK_HOLE query filesystem extent metadata directly without reading data blocks into RAM.
  3. Validate src_sz and slice bounds on sfd BEFORE opening dst with O_CREAT | O_TRUNC so errors leave dst untouched.

Tracing lseek Calls and Completing Lab 2

Check the exact boundary indices before executing: starting at byte 500, [500..1023] spans 524 zero bytes (slice[0..523] == 0x00), while slice[524] corresponds to file offset 1024 (0xff), advancing f_pos to 1524. Pipe input into STDIN_FILENO to trigger ESPIPE, count all 8 lseek calls under strace, and complete lab_m02_framed_copy.

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_patternsp1_enoent=1 p3_eexist=1 src_size=2048 dst_size=1024cur_after=1524 boundary=0x00,0xff ovf=1 ext=1 err=1,1learner@ksa:~/gl-c01/m02-l03printf 'stream' | strace -e trace=lseek ./offset_patterns 2>&1 | grep -c 'SEEK_'8learner@ksa:~/gl-c01/m02-l03rm -f offset_patternslearner@ksa:~/gl-c01/m02-l03

Lab 2: Byte-Exact Framed Slice Copier

env: host

1. Motivation

File-extraction and firmware-slicing utilities fail dangerously in the field when they open output files with O_CREAT | O_TRUNC before checking whether the input descriptor is seekable or holds enough bytes—wiping an existing configuration or firmware backup to 0 bytes whenever a user accidentally passes a pipe (ESPIPE) or an out-of-range offset! Compounding that bug, single-shot read()/write() calls drop bytes on partial transfers, strlen() truncates binary slices at 0x00, and decimal 644 scrambles inode permissions. Here you will build framed_copy, a side-effect-safe, binary-exact POSIX slice extractor.

2. Learning Objectives

  1. Implement EINTR- and short-count-resilient write_all() and read_full() loops over uint8_t buffers using signed ssize_t return checks.
  2. Validate input seekability (ESPIPE) and 64-bit off_t slice bounds (offset <= src_size and length <= src_size - offset) via lseek(src_fd, 0, SEEK_END) before opening or truncating dst_path.
  3. Enforce O_CLOEXEC, O_TRUNC, octal 0644 (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) permissions, and checked close() error propagation (EIO).

3. Environment Requirements

  • Host Execution Environment (Tested): Linux 6.12 LTS (x86_64, glibc 2.39+), #define _FILE_OFFSET_BITS 64 and #define _POSIX_C_SOURCE 200809L.
  • Target Board Portability (ARMv7 Cortex-A7): Defining _FILE_OFFSET_BITS 64 before all headers widens off_t from 32-bit long (2 GiB - 1 ceiling on ILP32 ARMv7) to signed 64-bit, enabling identical multi-gigabyte partition slicing on 32-bit embedded targets.

4. Required Software & Hardware

  • Software Toolchain: gcc (-std=c11 -Wall -Wextra -Werror), strace, cmp / sha256sum, stat, and /bin/sh.
  • Hardware: Standard Linux host environment (0 root privileges required).

5. Complete Executable Commands

Run from labs/lab_m02_framed_copy/:

learner@ksa: ~/gl-c01/m02-l03
learner@ksa:~/gl-c01/m02-l03$ bat script.sh File: script.sh    # 1. Compile the reference implementation with strict C11 and 64-bit off_t flags    gcc -std=c11 -O2 -Wall -Wextra -Werror files/framed_copy.c -o /tmp/framed_copy        # 2. Seed an 8 KiB binary file containing embedded 0x00 and 0xFF bytes    dd if=/dev/urandom of=/tmp/ksa_src.bin bs=1024 count=8 status=none        # 3. Extract exact 2048-byte window [500, 2548) and verify byte-for-byte identity    /tmp/framed_copy /tmp/ksa_src.bin /tmp/ksa_dst.bin 500 2048    dd if=/tmp/ksa_src.bin bs=1 skip=500 count=2048 status=none | cmp -s - /tmp/ksa_dst.bin && echo "MATCH_OK"        # 4. Verify side-effect safety: piped stdin fails with ESPIPE WITHOUT touching /tmp/ksa_dst.bin!    printf 'pipe_bytes' | /tmp/framed_copy /dev/stdin /tmp/ksa_dst.bin 0 4 || stat -c 'preserved_bytes=%s mode=%a' /tmp/ksa_dst.bin        # 5. Clean up scratch files and run the full TAP 13 test suite    rm -f /tmp/framed_copy /tmp/ksa_src.bin /tmp/ksa_dst.bin    sh check.sh

*Why each command runs:* dd generates arbitrary binary bytes (including 0x00); cmp -s proves byte-exact extraction at offset 500; piping /dev/stdin triggers ESPIPE on lseek() to verify /tmp/ksa_dst.bin keeps preserved_bytes=2048 and mode=644; and sh check.sh runs all automated checks.

6. Annotated Source Code (starter/ Flaws vs files/ Reference)

Flawed Baseline (starter/framed_copy.c)

  1. Destructive eager open(): Opens dst_fd on line 20 before checking whether src_fd is seekable or long enough.
  2. Decimal 644 & missing O_TRUNC/O_CLOEXEC: open(argv[2], O_WRONLY | O_CREAT, 644) stamps sticky octal 01204 (--w----r-T) and leaves stale trailing bytes intact when overwriting larger files!
  3. Unchecked atol() & strlen(buf): atol() invokes UB on overflow, fixed char buf[8192] overflows when length > 8192, and write(dst_fd, buf, strlen(buf)) truncates at the first 0x00 byte.

Warning-Clean Reference (files/framed_copy.c)

  • CLI Parsing (main): Parses <offset> with strtoll (errno == 0, *end == '\0', raw_off >= 0) and <length> with strtoull (<= SIZE_MAX).
  • Precondition Ordering (copy_slice): Opens src_fd (O_RDONLY | O_CLOEXEC), queries src_size = lseek(src_fd, 0, SEEK_END) (aborting immediately on ESPIPE!), validates subtraction bounds offset <= src_size && (uintmax_t)(src_size - offset) >= (uintmax_t)length (zero signed-overflow risk), seeks src_fd to offset, and only then opens dst_fd (O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644).
  • Streaming Loop & Checked close(): Streams 4,096-byte chunks through read_full() and write_all(), preserves errno across error-path close() calls, and verifies close(dst_fd) == 0 so deferred writeback EIO faults are never masked.

7. Expected Output

learner@ksa: ~/gl-c01/m02-l03
learner@ksa:~/gl-c01/m02-l03$ bat listing.txt File: listing.txt    $ sh check.sh    TAP version 13    1..6    ok 1 - compiles cleanly with -std=c11 -Wall -Wextra -Werror    ok 2 - copies binary slice with embedded 0x00 bytes and sets octal 0644 mode    ok 3 - truncates pre-existing larger destination file via O_TRUNC    ok 4 - rejects out-of-bounds slice without creating or modifying dst_path    ok 5 - rejects non-seekable pipe input (ESPIPE) without touching dst_path    ok 6 - handles 0-byte slice cleanly    # pass 6/6

8. Explanation of Observed Behavior

When copy_slice() runs against a 64 KiB binary file for [4096, 36864) (32 KiB), lseek(src_fd, 0, SEEK_END) reads inode->i_size in kernel RAM (0 disk I/O), lseek(src_fd, 4096, SEEK_SET) positions src_fd's struct file.f_pos to 4096, open(dst_path, ... | O_TRUNC, 0644) resets any prior destination extents and masks 0644 & ~umask, and eight 4 KiB iterations transfer all 32,768 bytes without ever scanning for '\0'. When /dev/stdin is a pipe, lseek(src_fd, 0, SEEK_END) returns (off_t)-1 with errno == ESPIPE at line 62—returning -1 before line 83 ever touches dst_path.

9. Experiment Variations

  1. Chunk-Size Syscall Trade-Off: Change uint8_t chunk[4096] to chunk[64] vs chunk[65536] on a 1 MiB slice and compare strace -c -e trace=read,write syscall counts (16,384 calls vs 256 calls vs 16 calls).
  2. umask Sensitivity Test: Run (umask 0077 && ./framed_copy src.bin dst.bin 0 64 && stat -c '%a' dst.bin) to confirm the kernel computes 0644 & ~0077 = 0600 (rw-------).
  3. Zero-Length Boundary: Run ./framed_copy src.bin empty.bin 2048 0 at exact EOF (offset == src_size, length == 0) to confirm a valid 0-byte file is created cleanly (copied=0).

10. Performance Measurements

Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 timed extractions of a 32 KiB slice from a 64 KiB file):

MetricMeasured Host (x86_64 Linux 6.12)Target Board Expectation (ARMv7 Cortex-A7 eMMC)
32 KiB slice CLI latency (p50 / p95 / p99)2,950.3 us / 3,299.9 us / 3,608.9 us~11,000–18,000 us (page-cache warm; higher on cold eMMC read)
Kernel lseek + read + write calls (32 KiB)2 + 8 + 8 (18 data-path syscalls)2 + 8 + 8 (_llseek on 32-bit ARMv7)

11. Troubleshooting

SymptomRoot CauseFix
Destination file shrinks to 0 bytes when offset is invalid`open(dst_path, ... \O_TRUNC) executed before lseek(src_fd, 0, SEEK_END)` bounds checkValidate src_size and bounds before opening dst_path
Output file has trailing stale bytes from an earlier runO_TRUNC omitted on open(dst_path, ...)Include `O_WRONLY \O_CREAT \O_TRUNC \O_CLOEXEC`
offset + length wraps negative on huge valuesSigned off_t overflow Undefined BehaviorCheck offset <= src_size first, then (uintmax_t)(src_size - offset) < length
Permissions show --w----r-T (1204)Passed decimal 644 instead of octal 0644Use 0644 or `S_IRUSR \S_IWUSR \S_IRGRP \S_IROTH`

12. Guided Questions

  1. Why does copy_slice() treat got < (ssize_t)want from read_full() as an error (EIO) even though we already verified offset + length <= src_size?
  • *Hint 1:* Can another process concurrently call ftruncate() on src_path between your SEEK_END check and your read_full() loop?
  • *Hint 2:* What does read_full() return if src_path shrinks mid-copy and hits premature EOF (0)?
  1. Why do we save int saved = errno; before calling close(src_fd) on error branches?
  • *Hint 1:* Check m03-l02's rules on whether close() can modify errno or leave callers guessing if close() itself hits an internal check.
  • *Hint 2:* Trace what perror("copy_slice") in main() prints if errno was overwritten during cleanup!

13. Independent Challenges

  1. Near Transfer — Atomic Staging Slice Extractor: Upgrade copy_slice() so that instead of truncating dst_path in place (which leaves a partial dst_path if SIGKILL hits mid-copy), it writes into <dst_path>.tmp.<pid> opened with O_CREAT | O_EXCL | O_CLOEXEC and atomically rename()s onto dst_path only after close() succeeds!
  2. Far Transfer — Zero-Copy Kernel copy_file_range(2) Fastpath: On Linux 4.5+ (#define _GNU_SOURCE), replace the user-space read_full/write_all 4 KiB bounce buffer with copy_file_range(src_fd, &in_off, dst_fd, NULL, left, 0) (falling back to read_full/write_all on EXDEV cross-filesystem copies) and benchmark 64 MiB throughput (MiB/s) with CLOCK_MONOTONIC.

14. Solutions & Explanations

  • Guided Question 1: Because Unix filesystems allow concurrent processes to truncate an open file without mandatory locking, read_full() returning < want detects concurrent truncation (EIO) instead of silently writing fewer bytes than copied=<length> promised.
  • Guided Question 2: Saving errno before close() guarantees perror("copy_slice") reports the exact root cause (ESPIPE, EINVAL, ENOSPC) rather than any side effect of cleanup.
  • Challenge 2 Key Idiom: ssize_t n = copy_file_range(src_fd, NULL, dst_fd, NULL, left, 0); copies page-cache folios (or issues filesystem CoW reflink clones on Btrfs/XFS) entirely inside Ring 0 with zero user-space memcpy() traffic!

Run locally in your terminal and check off each verification milestone.

Not started

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, extracting [500..1524) cleanly while rejecting negative offsets (EINVAL) and unseekable pipes (ESPIPE). That naturally raises the architectural focus of Module 3: where inside the Linux kernel does f_pos reside relative to on-disk inodes and directory entries, and how can user space inspect live f_pos and f_flags state via /proc/self/fdinfo/?

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 0 of an open seekable descriptor and restores fd's original f_pos before returning:

  1. Step 1 (Snapshot active f_pos): Call off_t saved = lseek(fd, 0, SEEK_CUR); and return -1 immediately if saved == (off_t)-1 (catching ESPIPE on pipes before moving anything).
  2. Step 2 (Rewind, read full 4 bytes, and restore): Seek to 0 (SEEK_SET), read 4 bytes via read_full(), and call lseek(fd, saved, SEEK_SET) on both the success path and any short-read path so callers never observe a mutated cursor.

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 last occurrence of a 4-byte marker "SYNC" inside an arbitrarily large regular file without reading from byte 0: query off_t end = lseek(fd, 0, SEEK_END), step backward in 4,096-byte windows (overlapping by 3 bytes across window seams so a "SYNC" straddling a 4 KiB boundary is never missed!), and print the exact 64-bit byte offset.

Common Production Pitfalls

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

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

Knowledge Check

quiz · 1 of 4

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

quiz · 2 of 4

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

quiz · 3 of 4

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?

quiz · 4 of 4

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?

Key takeaways

  • 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.
  • 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.
Progress is saved on this device.
up next · module 2 labLab: Byte-Exact Framed Slice Copier (45 min)
→ module 2 lab

search — fzf

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

keyboard shortcuts — less

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

figure