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.
What you'll learn
- Modify descriptor (
FD_CLOEXEC) and mutablestruct fileflags (O_APPEND,O_NONBLOCK) viafcntl()andO_ACCMODE. - Validate ABI-stable
ioctl()structs (_Static_assert, zeroed padding) alongsideFIONREADandTIOCGWINSZENOTTY. - Resize regular files with
ftruncate()andtruncate()while accounting for unchangedf_posand 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() Command | Kernel Tier Mutated | Mutable Bits & Immutability / Error Contract |
|---|---|---|
F_DUPFD / F_DUPFD_CLOEXEC | files_struct table | Allocates lowest free fd >= arg; _CLOEXEC sets FD_CLOEXEC atomically |
F_GETFD / F_SETFD | files_struct slot bit | Reads/writes FD_CLOEXEC on fd alone (aliases unaffected) |
F_GETFL / F_SETFL | Shared struct file.f_flags | Read-modify-write O_APPEND, O_NONBLOCK, O_ASYNC, O_DIRECT, O_NOATIME; O_ACCMODE is immutable |
ioctl(fd, FIONREAD, &n) | Subsystem / driver .unlocked_ioctl | Queries unread pipe/socket/TTY bytes; TIOCGWINSZ returns ENOTTY on non-TTYs |
ftruncate(fd, len) / truncate | struct inode.i_size | Requires writable fd (EINVAL/EBADF if O_RDONLY); f_pos stays unchanged! |
Figure 4.3. 32-bit _IOC command bitfield encoding, fcntl() Tier A vs Tier B flag control, and ftruncate() cursor invariants.
- Step 1. Clone or update per-slot FD_CLOEXEC via F_DUPFD_CLOEXEC and F_GETFD / F_SETFD without disturbing aliases.
- Step 2. Read fl = fcntl(fd, F_GETFL) before fcntl(fd, F_SETFL, fl | O_NONBLOCK) so O_APPEND is never wiped.
- Step 3. Lock _IOWR payload structs with fixed-width <stdint.h> types, explicit zeroed padding, and _Static_assert.
- 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) 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$ 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; }- Explicit reserved_zero padding + _Static_assert keeps sizeof(struct ksa_dev_cfg) == 16 across 32-bit ARMv7 and 64-bit x86-64.
- Read F_GETFL first and pass fl | O_APPEND to F_SETFL so existing mutable status flags are never wiped.
- 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-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→ open standalone lab workbench
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
- Enforce atomic mutual exclusion across processes using
open(..., O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600)and verifyEEXISTrejection on collision. - Verify per-descriptor
FD_CLOEXEC(F_GETFD) andO_ACCMODE/ clearO_APPENDstatus flags (F_GETFL) at runtime viafcntl(). - Execute short-count-safe
pwrite_all()andpread_full()operations across64-byte record slots while provinglseek(fd, 0, SEEK_CUR) == 0stays untouched. - Resize and compact the slot store cleanly using
ftruncate(fd, keep_slots * 64).
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64. - Target Board Portability (
ARMv7Cortex-A7): Fixed64-byteuint8_tslot framing (activebyte +char key[24]+char val[39],0compiler padding) and 64-bitpread/pwriteproduce byte-identical database files across 32-bitARMv7and 64-bitx86_64processes.
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$ 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)
- Broken lockfile (
lock-check): Callsopen(argv[2], O_WRONLY | O_CREAT, 0600)withoutO_EXCLorO_CLOEXEC, allowing two processes to open the lock simultaneously! - Stateful
lseek() + write()(put): Mutatesstruct file.f_pos(f_pos=640instead of0), omitsinitftruncate()sizing, and lacks bounds checks. - Missing
getandcompact: Unimplemented subcommands fail tests 3–5.
Warning-Clean Reference (files/atomic_kv.c)
acquire_lock()/release_lock(): Formats<db_path>.lockvia boundedsnprintf()(ret < 0 || (size_t)ret >= cap) and acquiresO_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC(0600).- Flag Guard (
put): Verifies(fl & O_APPEND) == 0viafcntl(fd, F_GETFL)—critical on Linux becausepwrite()ignoresoffsetifO_APPENDis set! - Stateless Slot I/O (
pwrite_all/pread_full): Transfers64bytes at(off_t)slot_idx * 64while advancing(p + done, off + done)on short counts/EINTR, then confirmslseek(fd, 0, SEEK_CUR) == 0and forces NUL termination (key[KEY_MAX - 1] = '\0') before printing untrusted disk bytes.
7. Expected Output
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/58. 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
- Linux
O_APPEND+pwrite()Quirk Reproduction: Temporarily add| O_APPENDtoopen()inside a scratch copy ofputand observepwrite(fd, raw, 64, 0)append at byte1,024instead of updating slot0—proving why(fl & O_APPEND) != 0must be rejected! - Concurrent Reader/Writer Stress Test: Spawn
4background reader loops running./atomic_kv get ... 0(100iterations each) while a writer updates slot0between"v1"and"v2", verifying0torn strings or cursor errors. - Stale Lockfile PID Inspection: Write the holder's
getpid()into<db_path>.lockbefore releasing so operators debugging a crashed holder can checkkill(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):
| Metric | Measured 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 / get | 1 / 1 (0 f_pos mutations) | 1 / 1 (pread64/pwrite64 EABI register pair) |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
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=0 | Called stateful write() instead of pwrite() | Use pwrite_all(fd, raw, 64, off) |
fcntl(fd, F_SETFD, O_CLOEXEC) fails to set FD_CLOEXEC | Passed 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
- Why must
fcntl(fd, F_SETFD, ...)receiveFD_CLOEXEC(1) whereasopen()receivesO_CLOEXEC(02000000)?
- *Hint 1:* Recall the two VFS flag tiers from
m04-l03(files_structper-slot bitmask vs open-timeflagsmultiplexer). - *Hint 2:* Print
(int)FD_CLOEXECand(int)O_CLOEXECin C: what happens to bit0(FD_CLOEXEC == 1) if you pass02000000(0x80000, bit0 == 0!) toF_SETFD?
- Why does
getdefensively setkey[KEY_MAX - 1] = '\0'aftermemcpy()from disk?
- *Hint 1:* Can an untrusted or bit-flipped database file on disk contain
24non-zero bytes inraw[1..24]? - *Hint 2:* What would
printf("key=%s", key)do ifkeylacked a'\0'byte?
13. Independent Challenges
- Near Transfer — Advisory Byte-Range Slot Locks (
F_SETLKW): Replace the coarse whole-file<db_path>.lockwith per-slotstruct flockbyte-range locks (l_type = F_WRLCK,l_whence = SEEK_SET,l_start = slot_idx * 64,l_len = 64) viafcntl(fd, F_SETLKW, &fl)so writers updating disjoint slots run concurrently! - Far Transfer — Directory-Pinned
*at()Store Engine: Refactoratomic_kv.cto open its parent directory once (O_RDONLY | O_DIRECTORY | O_CLOEXEC) and execute all lockfile and database operations viaopenat()andunlinkat(), closing path-prefix symlink swap vectors.
14. Solutions & Explanations
- Guided Question 1:
FD_CLOEXECequals1(bit 0), whereasO_CLOEXECequals0x80000(bit 19, bit0 == 0)! PassingO_CLOEXECtoF_SETFDactually clearsFD_CLOEXECto0—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'andval[VAL_MAX - 1] = '\0'guarantees%sformatting 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:
- Step 1 (Query & check
F_GETFL): Callint fl = fcntl(fd, F_GETFL);and return-1immediately whenfl == -1(preservingEBADF). - Step 2 (Compute
next_flcleanly): Computeint next_fl = enable ? (fl | O_NONBLOCK) : (fl & ~O_NONBLOCK);and callfcntl(fd, F_SETFL, next_fl)only ifnext_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
Key takeaways
fcntl()separates per-descriptor slot control (F_DUPFD_CLOEXEC,F_GETFD/F_SETFDforFD_CLOEXEC) from sharedstruct filestatus flags (F_GETFL/F_SETFL).F_SETFLtogglesO_APPEND,O_NONBLOCK,O_ASYNC,O_DIRECT, andO_NOATIMEvia read-modify-write, while(flags & O_ACCMODE)remains immutable afteropen().ioctl()dispatches out-of-band driver and subsystem queries (FIONREAD,TIOCGWINSZ) and fails withENOTTYon unsupported file types.- Custom
_IOR/_IOW/_IOWRUAPI structs encodesizeof(struct)into_IOC_SIZE(cmd), requiring<stdint.h>fixed-width fields, explicit reserved padding,memset(), and_Static_assert. ftruncate()(requiring a writablefd) andtruncate()resizeinode->i_sizewithout modifyingstruct file.f_pos.- Having mastered raw kernel descriptors across Modules 1–4, Module 5 steps back into
Ring 3to dissect howglibc<stdio.h>FILEstreams amortize syscall traps, handle binaryfread/fwritetails, and parse text safely.