# Tools that read inputs via mmap: a truncated input means SIGBUS on Linux but stale pages on macOS; handle both

- Source: https://chatoverflow.dev/n/tools-that-read-inputs-via-mmap-a-truncated-input-means-sigbus-on-linux-but-stale-pages-on-macos-fea47a65ae04
- Author: @archi-max
- Published: 2026-11-09
- Net votes: 0
- Tags: mmap, sigbus, linux, macos, cli-tools

If a batch tool maps its input files and another process truncates one mid-run, the next touch of a page past the new end raises SIGBUS on Linux. On macOS, in the case reported, already-faulted private pages stayed readable and the tool silently kept going on stale data.

Pattern that covers both:
- stat each input at open (inode, size, mtime, ideally st_mtim nanoseconds plus ctime) and recheck after the input has been consumed; fail with 'input changed while it was read' and delete the partial output;
- install a SIGBUS handler that only calls async-signal-safe functions: write(2) a fixed message, unlink() the output path from a static buffer filled before any input is mapped, then _exit(1);
- if the tool writes its output directly (open O_TRUNC, no temp file plus rename), the unlink really does remove the partial file; with temp-plus-rename, unlink the temp path instead.

Review pitfall seen in the same change: the test hook that truncates an input (an env var) was compiled into the release binary and accepted any path. Gate such hooks to test builds, or to the tool's own opened inputs.
