Descriptor Control: fcntl & ioctl

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.

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

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

Three runtime descriptor bugs ambush systems engineers regularly. First, a log forwarder enables non-blocking mode on an already-open O_WRONLY | O_APPEND descriptor by calling fcntl(fd, F_SETFL, O_NONBLOCK)—unwittingly clearing O_APPEND in struct file.f_flags so concurrent workers begin overwriting one another! Second, a vendor header defines struct motor_ioctl { unsigned long speed; uint16_t mode; }; inside #define MOTOR_SET _IOW('m', 1, struct motor_ioctl): a 32-bit ARMv7 diagnostic tool running under a 64-bit kernel fails every ioctl() with ENOTTY (Inappropriate ioctl for device) because sizeof(struct motor_ioctl) changed from 8 bytes to 16 bytes, altering the command integer itself! Third, compacting a 4,096-byte log via ftruncate(fd, 0) followed by write(fd, hdr, 32) injects a 4,096-byte leading sparse hole because ftruncate() never rewinds f_pos!

Controlling already-open descriptors cleanly requires respecting the VFS boundary between Tier A per-slot flags (F_GETFD/F_SETFD) and Tier B shared open-file flags (F_GETFL/F_SETFL), encoding ABI-invariant ioctl() UAPI structures, and repositioning f_pos explicitly after ftruncate().

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.

definition (fcntl() Flag Tiers, Out-of-Band ioctl() & ftruncate()): 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.

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 _IOWR(type, nr, data_type) request integer via cmd = (dir << 30) | (sizeof(data_type) << 16) | (type << 8) | nr. Bits [31:30] encode transfer direction (00 none, 01 write user->kernel, 10 read kernel->user, 11 read/write), bits [29:16] (14 bits, extracted via _IOC_SIZE(cmd)) store sizeof(struct), bits [15:8] store the 8-bit magic character ('k'), and bits [7:0] store the command ordinal! If a struct uses long, pointers, or implicit compiler padding holes (uint32_t + uint16_t + [2-byte hole] + uint64_t), either _IOC_SIZE(cmd) diverges across 32/64-bit builds (ENOTTY) or unzeroed stack padding leaks secrets across the ring boundary. Always use <stdint.h> fixed-width fields, explicit reserved_zero padding, memset(&cfg, 0, sizeof(cfg)), and _Static_assert(sizeof(...) == N).

Syscall / fcntl() CommandKernel Tier MutatedMutable Bits & Immutability / Error Contract
F_DUPFD / F_DUPFD_CLOEXECfiles_struct tableAllocates lowest free fd >= arg; _CLOEXEC sets FD_CLOEXEC atomically
F_GETFD / F_SETFDfiles_struct slot bitReads/writes FD_CLOEXEC on fd alone (aliases unaffected)
F_GETFL / F_SETFLShared struct file.f_flagsRead-modify-write O_APPEND, O_NONBLOCK, O_ASYNC, O_DIRECT, O_NOATIME; O_ACCMODE is immutable
ioctl(fd, FIONREAD, &n)Subsystem / driver .unlocked_ioctlQueries unread pipe/socket/TTY bytes; TIOCGWINSZ returns ENOTTY on non-TTYs
ftruncate(fd, len) / truncatestruct inode.i_sizeRequires writable fd (EINVAL/EBADF if O_RDONLY); f_pos stays unchanged!
fig_m04_l03_arch.svg — 32-bit _IOC command bitfield encoding, fcntl() Tier A…

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

step_m04_l03.svg — Separate per-slot FD_CLOEXEC from read-modify-write…step 1/4
  1. Step 1. Clone or update per-slot FD_CLOEXEC via F_DUPFD_CLOEXEC and F_GETFD / F_SETFD without disturbing aliases.
  2. Step 2. Read fl = fcntl(fd, F_GETFL) before fcntl(fd, F_SETFL, fl | O_NONBLOCK) so O_APPEND is never wiped.
  3. Step 3. Lock _IOWR payload structs with fixed-width <stdint.h> types, explicit zeroed padding, and _Static_assert.
  4. Step 4. Reposition f_pos via lseek() (or write via pwrite()) after shrinking inode->i_size with ftruncate().

Figure 4.3b. 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().

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/ioctl.h>. Remember: F_GETFD and F_GETFL return -1 on error (because valid bitmasks can be 0!), so check if (fl == -1) rather than fl <= 0 before ORing fl | O_APPEND into F_SETFL.

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). EINVAL Unrecognized cmd, negative ftruncate length,              or fd not writable. EMFILE F_DUPFD* minimum arg >= RLIMIT_NOFILE              or no free slots >= arg. NOTES       F_SETFL updates only O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME,       O_NONBLOCK; always read F_GETFL first so existing status flags are       preserved. SEE ALSO       dup3(2), ioctl(2), lseek(2), open(2) Kernel Systems Academy                   Lesson 4.3                   fcntl(2) GL-C01 quick reference · full manual page: man 2 fcntl 

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

Save desc_ctl.c below. It duplicates an open file to fd >= 40 via F_DUPFD_CLOEXEC (cloexec: 0->1), verifies (fl & O_ACCMODE) == O_RDWR and enables O_APPEND via read-modify-write F_SETFL, queries FIONREAD (19 piped bytes) and TIOCGWINSZ (ENOTTY) via ioctl(), validates _Static_assert(sizeof(struct ksa_dev_cfg) == 16) + _IOC_SIZE(KSA_IOC_CFG) == 16 + _IOC_DIR(KSA_IOC_CFG) == 3, and proves ftruncate(fd, 16) shrinks st_size from 32 to 16 while leaving f_pos at 32!

learner@ksa: ~/gl-c01/m04-l03
learner@ksa:~/gl-c01/m04-l03$ bat -H 18 -H 36 -H 56 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;        uint16_t flags;        uint16_t reserved_zero;        uint64_t cookie;  };    _Static_assert(sizeof(struct ksa_dev_cfg) == 16, "ABI size must be 16");    #define KSA_IOC_CFG _IOWR('k', 0x11, struct ksa_dev_cfg)        int main(void) {        const char *path = "/tmp/ksa_m04_l03.dat";        int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0644);        if (fd < 0) return 1;            int hi_fd = fcntl(fd, F_DUPFD_CLOEXEC, 40);        if (hi_fd < 40) return 1;        int fd_clo0 = (fcntl(fd, F_GETFD) & FD_CLOEXEC) ? 1 : 0;        int hi_clo1 = (fcntl(hi_fd, F_GETFD) & FD_CLOEXEC) ? 1 : 0;        if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) return 1;        (void)close(hi_fd);            int fl = fcntl(fd, F_GETFL);        if (fl == -1) return 1;      const char *acc = ((fl & O_ACCMODE) == O_RDWR) ? "O_RDWR" : "OTHER";        if (fcntl(fd, F_SETFL, fl | O_APPEND) < 0) return 1;        int fl_now = fcntl(fd, F_GETFL);        printf("fcntl_state: hi_ge40=yes cloexec=%d->%d acc=%s append=%d\n",               fd_clo0, hi_clo1, acc, (fl_now & O_APPEND) ? 1 : 0);            int queued = 0;        if (ioctl(STDIN_FILENO, FIONREAD, &queued) < 0) return 1;        struct winsize ws;        errno = 0;        int tty_rc = ioctl(STDIN_FILENO, TIOCGWINSZ, &ws);        int tty_err = errno;        struct ksa_dev_cfg cfg;        memset(&cfg, 0, sizeof(cfg));        unsigned int ioc_sz = (unsigned int)_IOC_SIZE(KSA_IOC_CFG);        printf("ioctl_probe: pipe_fionread=%d winsize_enotty=%s ioc_sz=%u\n",               queued, (tty_rc == -1 && tty_err == ENOTTY) ? "yes" : "no",               ioc_sz);            if (write(fd, "0123456789ABCDEF0123456789ABCDEF", 32) != 32) return 1;      off_t before = lseek(fd, 0, SEEK_CUR);        if (ftruncate(fd, 16) < 0) return 1;        off_t after = lseek(fd, 0, SEEK_CUR);        struct stat st;        if (fstat(fd, &st) < 0) return 1;        (void)close(fd);            if (truncate(path, 64) < 0 || stat(path, &st) < 0) return 1;        int rfd = open(path, O_RDONLY | O_CLOEXEC);        unsigned char zcheck = 0xFFU;        if (rfd < 0 || pread(rfd, &zcheck, 1, 48) != 1) return 1;        (void)close(rfd);        (void)unlink(path);            printf("resize_check: shrunk=16 f_pos=%lld->%lld ext=%lld zero=%u\n",               (long long)before, (long long)after,               (long long)st.st_size, (unsigned int)zcheck);        return 0;    }
  1. Explicit reserved_zero padding + _Static_assert keeps sizeof(struct ksa_dev_cfg) == 16 across 32-bit ARMv7 and 64-bit x86-64.
  2. Read F_GETFL first and pass fl | O_APPEND to F_SETFL so existing mutable status flags are never wiped.
  3. ftruncate(fd, 16) shrinks inode->i_size to 16 immediately while leaving struct file.f_pos untouched at 32.

Verifying Flag Bitmasks, FIONREAD, ftruncate & Lab 4

Compile desc_ctl.c, pipe a 19-byte payload (TELEMETRY_PING_2026) into STDIN_FILENO, verify every output line, and complete lab_m04_atomic_kv.

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_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-l03test ! -e /tmp/ksa_m04_l03.dat && rm -f desc_ctllearner@ksa:~/gl-c01/m04-l03

Lab 4: Race-Free Positional Record Store

env: host

1. Motivation

Embedded device-state registries and shared configuration stores suffer silent corruption when concurrent processes test lockfiles via access() + open() (TOCTOU race) or read and write fixed-size record slots via lseek() + write() (clobbering shared struct file.f_pos cursors on preemption). In this lab, you will engineer atomic_kv, a race-free 64-byte positional key-value store combining exclusive O_CREAT | O_EXCL | O_CLOEXEC lockfiles, fcntl() flag verification, stateless pwrite()/pread() transfers, and ftruncate() tail compaction.

2. Learning Objectives

  1. Enforce atomic mutual exclusion across processes using open(..., O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600) and verify EEXIST rejection on collision.
  2. Verify per-descriptor FD_CLOEXEC (F_GETFD) and O_ACCMODE / clear O_APPEND status flags (F_GETFL) at runtime via fcntl().
  3. Execute short-count-safe pwrite_all() and pread_full() operations across 64-byte record slots while proving lseek(fd, 0, SEEK_CUR) == 0 stays untouched.
  4. Resize and compact the slot store cleanly using ftruncate(fd, keep_slots * 64).

3. Environment Requirements

  • Host Execution Environment (Tested): Linux 6.12 LTS (x86_64, glibc 2.39+), #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64.
  • Target Board Portability (ARMv7 Cortex-A7): Fixed 64-byte uint8_t slot framing (active byte + char key[24] + char val[39], 0 compiler padding) and 64-bit pread/pwrite produce byte-identical database files across 32-bit ARMv7 and 64-bit x86_64 processes.

4. Required Software & Hardware

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

5. Complete Executable Commands

Run from labs/lab_m04_atomic_kv/:

learner@ksa: ~/gl-c01/m04-l03
learner@ksa:~/gl-c01/m04-l03$ bat script.sh File: script.sh    # 1. Compile the warning-clean positional record store    gcc -std=c11 -O2 -Wall -Wextra -Werror files/atomic_kv.c -o /tmp/atomic_kv        # 2. Verify atomic O_CREAT | O_EXCL | O_CLOEXEC lockfile and fcntl() inspection    /tmp/atomic_kv lock-check /tmp/ksa_test.lock        # 3. Initialize a 16-slot (1,024-byte) database, populate slots 0 and 9, and query slot 9    /tmp/atomic_kv init /tmp/ksa_kv.db 16    /tmp/atomic_kv put /tmp/ksa_kv.db 0 board_rev v2.4    /tmp/atomic_kv put /tmp/ksa_kv.db 9 vcore_mv 1200    /tmp/atomic_kv get /tmp/ksa_kv.db 9        # 4. Compact database to 4 slots (256 bytes) and confirm slot 9 is now out-of-bounds (rc=1)    /tmp/atomic_kv compact /tmp/ksa_kv.db 4    /tmp/atomic_kv get /tmp/ksa_kv.db 0    /tmp/atomic_kv get /tmp/ksa_kv.db 9 || echo "slot_9_compacted_ok"        # 5. Clean up and execute the full TAP 13 verification suite    rm -f /tmp/atomic_kv /tmp/ksa_kv.db /tmp/ksa_kv.db.lock    sh check.sh

*Why each command runs:* lock-check proves duplicate O_CREAT | O_EXCL fails with EEXIST and fcntl() reads FD_CLOEXEC + O_WRONLY; init uses ftruncate() to create a zero-filled 1,024-byte slot table; put/get prove pwrite()/pread() leave f_pos=0; and compact shrinks inode->i_size to 256 bytes while preserving slot 0.

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

Flawed Baseline (starter/atomic_kv.c)

  1. Broken lockfile (lock-check): Calls open(argv[2], O_WRONLY | O_CREAT, 0600) without O_EXCL or O_CLOEXEC, allowing two processes to open the lock simultaneously!
  2. Stateful lseek() + write() (put): Mutates struct file.f_pos (f_pos=640 instead of 0), omits init ftruncate() sizing, and lacks bounds checks.
  3. Missing get and compact: Unimplemented subcommands fail tests 3–5.

Warning-Clean Reference (files/atomic_kv.c)

  • acquire_lock() / release_lock(): Formats <db_path>.lock via bounded snprintf() (ret < 0 || (size_t)ret >= cap) and acquires O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC (0600).
  • Flag Guard (put): Verifies (fl & O_APPEND) == 0 via fcntl(fd, F_GETFL)—critical on Linux because pwrite() ignores offset if O_APPEND is set!
  • Stateless Slot I/O (pwrite_all / pread_full): Transfers 64 bytes at (off_t)slot_idx * 64 while advancing (p + done, off + done) on short counts/EINTR, then confirms lseek(fd, 0, SEEK_CUR) == 0 and forces NUL termination (key[KEY_MAX - 1] = '\0') before printing untrusted disk bytes.

7. Expected Output

learner@ksa: ~/gl-c01/m04-l03
learner@ksa:~/gl-c01/m04-l03$ bat listing.txt File: listing.txt    $ sh check.sh    TAP version 13    1..5    ok 1 - builds cleanly with -std=c11 -Wall -Wextra -Werror    ok 2 - enforces atomic O_CREAT|O_EXCL|O_CLOEXEC lockfile and fcntl inspection    ok 3 - initializes fixed-slot store and executes stateless pwrite/pread leaving f_pos=0    ok 4 - rejects empty, negative, and out-of-bounds slot queries cleanly    ok 5 - compacts tail slots via ftruncate while preserving earlier records    # pass 5/5

8. Explanation of Observed Behavior

Under strace -e trace=openat,fcntl,pwrite64,pread64,ftruncate,lseek, init extends <db_path> to slots * 64 sparse zero bytes in 1 ftruncate() call (active == 0 in every slot). Each put writes a self-contained 64-byte record via pwrite64(fd, raw, 64, slot * 64) using stack-local kiocb.ki_pos, so lseek(fd, 0, SEEK_CUR) afterward still reports 0 (f_pos=0). Note that get needs no lockfile when 64-byte aligned writes stay within a single 4 KiB page-cache folio under i_rwsem or when callers coordinate single-slot updates, and pread64 never contends on file->f_pos_lock.

9. Experiment Variations

  1. Linux O_APPEND + pwrite() Quirk Reproduction: Temporarily add | O_APPEND to open() inside a scratch copy of put and observe pwrite(fd, raw, 64, 0) append at byte 1,024 instead of updating slot 0—proving why (fl & O_APPEND) != 0 must be rejected!
  2. Concurrent Reader/Writer Stress Test: Spawn 4 background reader loops running ./atomic_kv get ... 0 (100 iterations each) while a writer updates slot 0 between "v1" and "v2", verifying 0 torn strings or cursor errors.
  3. Stale Lockfile PID Inspection: Write the holder's getpid() into <db_path>.lock before releasing so operators debugging a crashed holder can check kill(pid, 0) (ESRCH).

10. Performance Measurements

Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 paired put + get CLI transactions on a 64-slot 4 KiB store):

MetricMeasured Host (x86_64 Linux 6.12)Target Board Expectation (ARMv7 Cortex-A7)
Paired put + get CLI latency (p50 / p95 / p99)3,794.9 us / 4,827.7 us / 4,850.6 us~15,000–22,000 us (2 process spawns; < 4 us in-process pread/pwrite)
pwrite64 / pread64 syscalls per put / get1 / 1 (0 f_pos mutations)1 / 1 (pread64/pwrite64 EABI register pair)

11. Troubleshooting

SymptomRoot CauseFix
put fails immediately on subsequent calls (rc=1)Forgot to unlink(lock_path) inside release_lock(), leaving .lock on disk (EEXIST)Always close(lock_fd) and unlink(lock_path) on every exit path
PUT prints f_pos=64 instead of f_pos=0Called stateful write() instead of pwrite()Use pwrite_all(fd, raw, 64, off)
fcntl(fd, F_SETFD, O_CLOEXEC) fails to set FD_CLOEXECPassed O_CLOEXEC (02000000) instead of FD_CLOEXEC (1) to F_SETFD!Pass O_CLOEXEC to open()/dup3(), and FD_CLOEXEC to fcntl(F_SETFD)!

12. Guided Questions

  1. Why must fcntl(fd, F_SETFD, ...) receive FD_CLOEXEC (1) whereas open() receives O_CLOEXEC (02000000)?
  • *Hint 1:* Recall the two VFS flag tiers from m04-l03 (files_struct per-slot bitmask vs open-time flags multiplexer).
  • *Hint 2:* Print (int)FD_CLOEXEC and (int)O_CLOEXEC in C: what happens to bit 0 (FD_CLOEXEC == 1) if you pass 02000000 (0x80000, bit 0 == 0!) to F_SETFD?
  1. Why does get defensively set key[KEY_MAX - 1] = '\0' after memcpy() from disk?
  • *Hint 1:* Can an untrusted or bit-flipped database file on disk contain 24 non-zero bytes in raw[1..24]?
  • *Hint 2:* What would printf("key=%s", key) do if key lacked a '\0' byte?

13. Independent Challenges

  1. Near Transfer — Advisory Byte-Range Slot Locks (F_SETLKW): Replace the coarse whole-file <db_path>.lock with per-slot struct flock byte-range locks (l_type = F_WRLCK, l_whence = SEEK_SET, l_start = slot_idx * 64, l_len = 64) via fcntl(fd, F_SETLKW, &fl) so writers updating disjoint slots run concurrently!
  2. Far Transfer — Directory-Pinned *at() Store Engine: Refactor atomic_kv.c to open its parent directory once (O_RDONLY | O_DIRECTORY | O_CLOEXEC) and execute all lockfile and database operations via openat() and unlinkat(), closing path-prefix symlink swap vectors.

14. Solutions & Explanations

  • Guided Question 1: FD_CLOEXEC equals 1 (bit 0), whereas O_CLOEXEC equals 0x80000 (bit 19, bit 0 == 0)! Passing O_CLOEXEC to F_SETFD actually clears FD_CLOEXEC to 0—one of the subtlest macro mix-ups in POSIX C!
  • Guided Question 2: Disk files are untrusted external inputs; clamping key[KEY_MAX - 1] = '\0' and val[VAL_MAX - 1] = '\0' guarantees %s formatting can never overread stack memory even on a corrupted image.

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

Not started

Kernel Mechanics Across fcntl, ioctl & Inode Resizing

In desc_ctl, F_DUPFD_CLOEXEC scanned files_struct starting at slot 40 and set FD_CLOEXEC atomically on hi_fd while leaving fd's slot bit 0. Next, F_GETFL + F_SETFL toggled O_APPEND on struct file.f_flags without disturbing O_RDWR, FIONREAD inspected the kernel pipe buffer's unread byte count (19) without consuming input, and ftruncate(fd, 16) proved f_pos remains at 32 unless repositioned!

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 disturbing O_APPEND or O_DIRECT:

  1. Step 1 (Query & check F_GETFL): Call int fl = fcntl(fd, F_GETFL); and return -1 immediately when fl == -1 (preserving EBADF).
  2. Step 2 (Compute next_fl cleanly): Compute int next_fl = enable ? (fl | O_NONBLOCK) : (fl & ~O_NONBLOCK); and call fcntl(fd, F_SETFL, next_fl) only if next_fl != fl (saving a redundant syscall when already in the target state!).

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 request constants (FIONREAD, TIOCGWINSZ, and a custom _IOWR('s', 0x2A, struct sensor_cal)), extracts _IOC_DIR(cmd), _IOC_TYPE(cmd), _IOC_NR(cmd), and _IOC_SIZE(cmd), and verifies with _Static_assert that offsetof and sizeof(struct sensor_cal) contain zero unnamed compiler padding bytes.

Common Production Pitfalls

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

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

Knowledge Check

quiz · 1 of 4

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

quiz · 2 of 4

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

quiz · 3 of 4

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

quiz · 4 of 4

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?

Key takeaways

  • 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.
  • 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.
Progress is saved on this device.
up next · module 4 labLab: Race-Free Positional Record Store (45 min)
→ module 4 lab

search — fzf

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

keyboard shortcuts — less

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

figure