Lab 4: Race-Free Positional Record Store
Control kernel open-file table sharing across dual opens and dup/dup2/dup3, eliminate TOCTOU and offset races with O_EXCL and stateless pread/pwrite, and manipulate live descriptors with fcntl, ioctl, and ftruncate.
Prerequisites in this module
What ./check.sh verifies
- Clean C11 build with
-std=c11 -Wall -Wextra -Werrorand zero warnings. - Runtime behavior, exit status, and output match the automated
./check.shassertions.
step 1/15 · inspect starter files and specification
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.
learner@ksa:~/gl-c01/lab-m04ls -lastarter/atomic_kv.clearner@ksa:~/gl-c01/lab-m04starter: starter/atomic_kv.c
learner@ksa:~/gl-c01/lab-m04$ bat starter/atomic_kv.c File: starter/atomic_kv.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 <unistd.h> enum { SLOT_BYTES = 64, KEY_MAX = 24, VAL_MAX = 39 }; struct slot_rec { uint8_t active; char key[KEY_MAX]; char val[VAL_MAX]; }; /* * STARTER BASELINE (contains intentional systems bugs): * 1. lock-check omits O_EXCL and O_CLOEXEC, failing duplicate-lock and fcntl checks. * 2. put uses lseek() + write() instead of stateless pwrite(), mutating f_pos. * 3. get and compact are not yet implemented. */ int main(int argc, char **argv) { if (argc < 3) { return 2; } const char *cmd = argv[1]; if (strcmp(cmd, "lock-check") == 0 && argc == 3) { int fd1 = open(argv[2], O_WRONLY | O_CREAT, 0600); int fd2 = open(argv[2], O_WRONLY | O_CREAT, 0600); if (fd1 >= 0) close(fd1); if (fd2 >= 0) close(fd2); unlink(argv[2]); printf("LOCK_EXCL broken_duplicate_open_succeeded\n"); return 0; } if (strcmp(cmd, "init") == 0 && argc == 4) { int fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0644); if (fd < 0) return 1; close(fd); printf("INIT slots=0 bytes=0\n"); return 0; } if (strcmp(cmd, "put") == 0 && argc == 6) { long idx = strtol(argv[3], NULL, 10); int fd = open(argv[2], O_RDWR); if (fd < 0) return 1; struct slot_rec rec; memset(&rec, 0, sizeof(rec)); rec.active = 1U; snprintf(rec.key, sizeof(rec.key), "%s", argv[4]); snprintf(rec.val, sizeof(rec.val), "%s", argv[5]); lseek(fd, (off_t)idx * SLOT_BYTES, SEEK_SET); if (write(fd, &rec, sizeof(rec)) != (ssize_t)sizeof(rec)) { close(fd); return 1; } off_t cur = lseek(fd, 0, SEEK_CUR); close(fd); printf("PUT slot=%ld f_pos=%lld\n", idx, (long long)cur); return 0; } fprintf(stderr, "unimplemented subcommand: %s\n", cmd); return 1; }step 2/15 · 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).
step 3/15 · 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.
step 4/15 · 4. required software & hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,stat, and/bin/sh. - Hardware: Standard Linux host environment.
step 5/15 · 5. complete executable commands
Run from labs/lab_m04_atomic_kv/:
learner@ksa:~/gl-c01/lab-m04$ 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.
step 6/15 · 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.
step 7/15 · 7. expected output
learner@ksa:~/gl-c01/lab-m04$ 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/5step 8/15 · 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.
step 9/15 · 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).
step 10/15 · 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) |
step 11/15 · 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)! |
step 12/15 · 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?
step 13/15 · 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.
step 14/15 · 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.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-c01/lab-m04./atomic_kv init store.db 6 && ./atomic_kv put store.db 4 psu.vout 12100mV && ./atomic_kv get store.db 4learner@ksa:~/gl-c01/lab-m04INIT slots=6 bytes=384PUT slot=4 f_pos=0GET slot=4 key=psu.vout val=12100mV f_pos=0Progressive hints & solution
hint 1
Compare starter/atomic_kv.c against the module lessons. Focus first on: Clean C11 build with -std=c11 -Wall -Wextra -Werror and zero warnings.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/atomic_kv.c
learner@ksa:~/gl-c01/lab-m04$ bat files/atomic_kv.c File: files/atomic_kv.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> enum { SLOT_BYTES = 64, KEY_MAX = 24, VAL_MAX = 39 }; struct slot_rec { uint8_t active; char key[KEY_MAX]; char val[VAL_MAX]; }; static int parse_nonneg_long(const char *s, long *out) { if (!s || *s == '\0') return -1; errno = 0; char *end = NULL; long v = strtol(s, &end, 10); if (errno != 0 || end == s || *end != '\0' || v < 0) return -1; *out = v; return 0; } static int acquire_lock(const char *db_path, char *lock_buf, size_t cap) { int n = snprintf(lock_buf, cap, "%s.lock", db_path); if (n < 0 || (size_t)n >= cap) return -1; return open(lock_buf, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); } static void release_lock(int lock_fd, const char *lock_path) { if (lock_fd >= 0) close(lock_fd); if (lock_path && *lock_path) unlink(lock_path); } static int pwrite_all(int fd, const void *buf, size_t len, off_t off) { const uint8_t *p = (const uint8_t *)buf; size_t done = 0; while (done < len) { ssize_t n = pwrite(fd, p + done, len - done, off + (off_t)done); if (n < 0) { if (errno == EINTR) continue; return -1; } done += (size_t)n; } return 0; } static int pread_full(int fd, void *buf, size_t len, off_t off) { uint8_t *p = (uint8_t *)buf; size_t done = 0; while (done < len) { ssize_t n = pread(fd, p + done, len - done, off + (off_t)done); if (n < 0) { if (errno == EINTR) continue; return -1; } if (n == 0) return -1; done += (size_t)n; } return 0; } int main(int argc, char **argv) { if (argc < 3) return 2; const char *cmd = argv[1]; if (strcmp(cmd, "lock-check") == 0 && argc == 3) { const char *lpath = argv[2]; int fd1 = open(lpath, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); if (fd1 < 0) return 1; int fd_flags = fcntl(fd1, F_GETFD); int fl_flags = fcntl(fd1, F_GETFL); if (fd_flags < 0 || fl_flags < 0) { close(fd1); unlink(lpath); return 1; } int fd2 = open(lpath, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); int second_err = errno; if (fd2 != -1 || second_err != EEXIST) { if (fd2 >= 0) close(fd2); close(fd1); unlink(lpath); return 1; } int cloexec = (fd_flags & FD_CLOEXEC) ? 1 : 0; const char *mode = ((fl_flags & O_ACCMODE) == O_WRONLY) ? "O_WRONLY" : "OTHER"; close(fd1); unlink(lpath); if (!cloexec || strcmp(mode, "O_WRONLY") != 0) return 1; printf("LOCK_EXCL ok cloexec=%d mode=%s\n", cloexec, mode); return 0; } if (strcmp(cmd, "init") == 0 && argc == 4) { long slots = 0; if (parse_nonneg_long(argv[3], &slots) < 0 || slots > 65536) return 1; char lock_path[PATH_MAX]; int lfd = acquire_lock(argv[2], lock_path, sizeof(lock_path)); if (lfd < 0) return 1; int fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) { release_lock(lfd, lock_path); return 1; } off_t bytes = (off_t)slots * SLOT_BYTES; if (ftruncate(fd, bytes) < 0) { close(fd); release_lock(lfd, lock_path); return 1; } close(fd); release_lock(lfd, lock_path); printf("INIT slots=%ld bytes=%lld\n", slots, (long long)bytes); return 0; } if (strcmp(cmd, "put") == 0 && argc == 6) { long slot_idx = 0; if (parse_nonneg_long(argv[3], &slot_idx) < 0) return 1; size_t klen = strlen(argv[4]); size_t vlen = strlen(argv[5]); if (klen == 0 || klen >= KEY_MAX || vlen >= VAL_MAX) return 1; char lock_path[PATH_MAX]; int lfd = acquire_lock(argv[2], lock_path, sizeof(lock_path)); if (lfd < 0) return 1; int fd = open(argv[2], O_RDWR | O_CLOEXEC); if (fd < 0) { release_lock(lfd, lock_path); return 1; } int fl = fcntl(fd, F_GETFL); struct stat st; if (fl < 0 || (fl & O_APPEND) != 0 || fstat(fd, &st) < 0) { close(fd); release_lock(lfd, lock_path); return 1; } off_t off = (off_t)slot_idx * SLOT_BYTES; if (off + SLOT_BYTES > st.st_size) { close(fd); release_lock(lfd, lock_path); return 1; } uint8_t raw[SLOT_BYTES]; memset(raw, 0, sizeof(raw)); raw[0] = 1U; memcpy(raw + 1, argv[4], klen); memcpy(raw + 1 + KEY_MAX, argv[5], vlen); if (pwrite_all(fd, raw, SLOT_BYTES, off) < 0) { close(fd); release_lock(lfd, lock_path); return 1; } off_t cur = lseek(fd, 0, SEEK_CUR); close(fd); release_lock(lfd, lock_path); if (cur != 0) return 1; printf("PUT slot=%ld f_pos=%lld\n", slot_idx, (long long)cur); return 0; } if (strcmp(cmd, "get") == 0 && argc == 4) { long slot_idx = 0; if (parse_nonneg_long(argv[3], &slot_idx) < 0) return 1; int fd = open(argv[2], O_RDONLY | O_CLOEXEC); if (fd < 0) return 1; struct stat st; off_t off = (off_t)slot_idx * SLOT_BYTES; if (fstat(fd, &st) < 0 || off + SLOT_BYTES > st.st_size) { close(fd); return 1; } uint8_t raw[SLOT_BYTES]; if (pread_full(fd, raw, SLOT_BYTES, off) < 0) { close(fd); return 1; } off_t cur = lseek(fd, 0, SEEK_CUR); close(fd); if (cur != 0 || raw[0] != 1U) return 1; char key[KEY_MAX]; char val[VAL_MAX]; memcpy(key, raw + 1, KEY_MAX); key[KEY_MAX - 1] = '\0'; memcpy(val, raw + 1 + KEY_MAX, VAL_MAX); val[VAL_MAX - 1] = '\0'; printf("GET slot=%ld key=%s val=%s f_pos=%lld\n", slot_idx, key, val, (long long)cur); return 0; } if (strcmp(cmd, "compact") == 0 && argc == 4) { long keep_slots = 0; if (parse_nonneg_long(argv[3], &keep_slots) < 0 || keep_slots > 65536) return 1; char lock_path[PATH_MAX]; int lfd = acquire_lock(argv[2], lock_path, sizeof(lock_path)); if (lfd < 0) return 1; int fd = open(argv[2], O_RDWR | O_CLOEXEC); if (fd < 0) { release_lock(lfd, lock_path); return 1; } off_t new_bytes = (off_t)keep_slots * SLOT_BYTES; if (ftruncate(fd, new_bytes) < 0) { close(fd); release_lock(lfd, lock_path); return 1; } close(fd); release_lock(lfd, lock_path); printf("COMPACT bytes=%lld\n", (long long)new_bytes); return 0; } return 2; }Run the check
From labs/lab_m04_atomic_kv/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-c01/lab-m04./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lockok 3 - zero-extends 6-slot store to 384 bytes via ftruncateok 4 - performs stateless pwrite/pread slot I/O leaving f_pos at 0ok 5 - compacts store to 128 bytes via ftruncate while preserving slot 1# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-c01/lab-m04./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsnot ok 2 - enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lock --- message: 'lock-check returned LOCK_EXCL broken_duplicate_open_succeeded (stale lock exists: no)' hint: 'open with O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, inspect F_GETFD/F_GETFL via fcntl(), and unlink before exit' ...not ok 3 - zero-extends 6-slot store to 384 bytes via ftruncate --- message: 'init output= INIT slots=0 bytes=0 size=0, expected INIT slots=6 bytes=384 and 384 bytes' hint: 'call ftruncate(fd, slots * 64) to size the backing file cleanly' ...not ok 4 - performs stateless pwrite/pread slot I/O leaving f_pos at 0 --- message: 'put= PUT slot=4 f_pos=320 get= empty inactive_rejected=1' hint: 'use pwrite()/pread() at slot*64 without mutating f_pos and exit non-zero on inactive slots' ...not ok 5 - compacts store to 128 bytes via ftruncate while preserving slot 1 --- message: 'compact= empty size=320 slot1= empty' hint: 'shrink store.db to keep_slots * 64 via ftruncate() without altering earlier slots' ...# pass 1/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-c01/lab-m04$ bat check.sh File: check.sh #!/bin/sh set -u PASS=0 TOTAL=5 tap_ok() { PASS=$((PASS + 1)) printf 'ok %s - %s\n' "$1" "$2" } tap_not_ok() { msg=$(printf '%s' "$3" | tr "\n\r'" " " | sed "s/ */ /g; s/^ //; s/ \$//") hnt=$(printf '%s' "$4" | tr "\n\r'" " " | sed "s/ */ /g; s/^ //; s/ \$//") printf 'not ok %s - %s\n' "$1" "$2" printf ' ---\n' printf " message: '%s'\n" "$msg" printf " hint: '%s'\n" "$hnt" printf ' ...\n' } printf 'TAP version 13\n' printf '1..%s\n' "$TOTAL" WORK="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_m04.XXXXXX")" trap 'rm -rf "$WORK"' EXIT BUILT=0 if [ ! -f files/atomic_kv.c ]; then tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "missing files/atomic_kv.c" \ "place your implementation in files/atomic_kv.c" elif gcc -std=c11 -Wall -Wextra -Werror files/atomic_kv.c -o "$WORK/atomic_kv" 2>"$WORK/gcc.err"; then BUILT=1 tap_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" else tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "gcc failed: $(cat "$WORK/gcc.err")" \ "fix all C11 warnings and errors in files/atomic_kv.c" fi LOCK_OUT="" if [ "$BUILT" -eq 1 ]; then LOCK_OUT="$(timeout 3 "$WORK/atomic_kv" lock-check "$WORK/test.lock" 2>/dev/null || true)" fi if [ "$LOCK_OUT" = "LOCK_EXCL ok cloexec=1 mode=O_WRONLY" ] && [ ! -e "$WORK/test.lock" ]; then tap_ok 2 "enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lock" else tap_not_ok 2 "enforces O_CREAT|O_EXCL|O_CLOEXEC lockfile check and unlinks lock" \ "lock-check returned '${LOCK_OUT:-empty}' (stale lock exists: $([ -e "$WORK/test.lock" ] && echo yes || echo no))" \ "open with O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC, inspect F_GETFD/F_GETFL via fcntl(), and unlink before exit" fi INIT_OUT="" INIT_BYTES=0 if [ "$BUILT" -eq 1 ]; then INIT_OUT="$(timeout 3 "$WORK/atomic_kv" init "$WORK/store.db" 6 2>/dev/null || true)" [ -f "$WORK/store.db" ] && INIT_BYTES="$(wc -c < "$WORK/store.db" | tr -d ' ')" fi if [ "$INIT_OUT" = "INIT slots=6 bytes=384" ] && [ "$INIT_BYTES" = "384" ]; then tap_ok 3 "zero-extends 6-slot store to 384 bytes via ftruncate" else tap_not_ok 3 "zero-extends 6-slot store to 384 bytes via ftruncate" \ "init output='${INIT_OUT:-empty}' size=${INIT_BYTES}, expected 'INIT slots=6 bytes=384' and 384 bytes" \ "call ftruncate(fd, slots * 64) to size the backing file cleanly" fi PUT_OUT="" GET_OUT="" INACTIVE_OK=0 if [ "$BUILT" -eq 1 ] && [ -f "$WORK/store.db" ]; then PUT_OUT="$(timeout 3 "$WORK/atomic_kv" put "$WORK/store.db" 4 "psu.vout" "12100mV" 2>/dev/null || true)" timeout 3 "$WORK/atomic_kv" put "$WORK/store.db" 1 "fan.tach" "4200rpm" >/dev/null 2>&1 || true GET_OUT="$(timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 4 2>/dev/null || true)" if ! timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 2 >/dev/null 2>&1; then INACTIVE_OK=1 fi fi if [ "$PUT_OUT" = "PUT slot=4 f_pos=0" ] && [ "$GET_OUT" = "GET slot=4 key=psu.vout val=12100mV f_pos=0" ] && [ "$INACTIVE_OK" -eq 1 ]; then tap_ok 4 "performs stateless pwrite/pread slot I/O leaving f_pos at 0" else tap_not_ok 4 "performs stateless pwrite/pread slot I/O leaving f_pos at 0" \ "put='${PUT_OUT:-empty}' get='${GET_OUT:-empty}' inactive_rejected=${INACTIVE_OK}" \ "use pwrite()/pread() at slot*64 without mutating f_pos and exit non-zero on inactive slots" fi COMP_OUT="" COMP_BYTES=0 GET1_OUT="" SLOT4_GONE=0 if [ "$BUILT" -eq 1 ] && [ -f "$WORK/store.db" ]; then COMP_OUT="$(timeout 3 "$WORK/atomic_kv" compact "$WORK/store.db" 2 2>/dev/null || true)" COMP_BYTES="$(wc -c < "$WORK/store.db" | tr -d ' ')" if ! timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 4 >/dev/null 2>&1; then SLOT4_GONE=1 fi GET1_OUT="$(timeout 3 "$WORK/atomic_kv" get "$WORK/store.db" 1 2>/dev/null || true)" fi if [ "$COMP_OUT" = "COMPACT bytes=128" ] && [ "$COMP_BYTES" = "128" ] && [ "$SLOT4_GONE" -eq 1 ] && [ "$GET1_OUT" = "GET slot=1 key=fan.tach val=4200rpm f_pos=0" ]; then tap_ok 5 "compacts store to 128 bytes via ftruncate while preserving slot 1" else tap_not_ok 5 "compacts store to 128 bytes via ftruncate while preserving slot 1" \ "compact='${COMP_OUT:-empty}' size=${COMP_BYTES} slot1='${GET1_OUT:-empty}'" \ "shrink store.db to keep_slots * 64 via ftruncate() without altering earlier slots" fi printf '# pass %s/%s\n' "$PASS" "$TOTAL" [ "$PASS" -eq "$TOTAL" ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m04_atomic_kv/ so relative paths to files/ resolve directly.