Skip to content

Latest commit

 

History

History
129 lines (103 loc) · 8.24 KB

tmp_run_dir.md

File metadata and controls

129 lines (103 loc) · 8.24 KB

tmp_run_dir.sh

Revision: 1 Last modified: 2026-12-04T18:15:21Z

Overview

This is a library. It is sourced, never executed. Mode rw-rw-r--. Bash only — see the shell contract below.

It creates one per-run temp directory, points TMPDIR at it, and removes it on EXIT, INT, TERM and HUP.

It exists because of a measured leak class (TMP-LEAK-07): a script or test that calls mktemp -d many times — often inside $(...), where a registration array is lost — and relies on trap … EXIT, leaks directories whenever it is killed or a subshell hides the path. With this helper, every mktemp in the script and in its children (including a child later killed by SIGKILL) allocates inside the one directory, so a single removal reclaims all of it.

SIGKILL cannot be trapped: the run directory then survives — but it is one directory under the original TMPDIR instead of hundreds. Removal uses safe_rm_rf (§11.4.287) on the ${TMP_RUN_DIR:?}-guarded path, with TMPDIR restored first, because safe_rm_rf refuses to delete the temp root itself.

Prerequisites

  • Bash ≥ 4 (bash 5.3 is what the test suite runs on). A non-bash shell (dash, busybox sh) gets a diagnostic on stderr and a return of 1 before any bash-only syntax is parsed — no run dir is created and nothing is chained, so sourcing it from sh cannot produce a parse error mid-file.
  • mktemp, safe_rm_rf (sourced automatically from safe_rm.sh beside this file).
  • bash < 4 (no $BASHPID, e.g. macOS /bin/bash 3.2) is UNCONFIRMED: — there was no such bash on the development host; the missing-$BASHPID path was exercised only by unset BASHPID. There the signal is re-raised through a direct sh -c 'kill -s SIG "$PPID"' child; if even that cannot kill the process, a diagnostic is printed and the process exits 128+N, i.e. the behaviour difference is announced, never silent. Whether $(trap -p EXIT) shows the current shell's trap on bash 3.2 is also UNCONFIRMED: — if it does not, a caller EXIT trap installed before init is not chained there.

Usage examples

. "$REPO/scripts/lib/tmp_run_dir.sh"

tmp_run_dir_init "myscript" || exit 2   # sets and exports TMP_RUN_DIR, exports TMPDIR=$TMP_RUN_DIR
mktemp -d                               # lands inside $TMP_RUN_DIR
tmp_run_dir_cleanup                     # optional early removal (also runs from the traps)

Exit codes / return values

Function Returns Effect
(sourcing in a non-bash shell) 1 (or exit 1 when not sourceable) diagnostic on stderr; nothing created, nothing chained
(sourcing twice in one shell) 0 the second source is a no-op, so the first run dir and its chained caller trap are not forgotten
tmp_run_dir_init PREFIX 0 TMP_RUN_DIR set and exported; TMPDIR exported as the run dir; EXIT/INT/TERM/HUP traps armed
0 (again) idempotent — exactly one run dir per process
1 mktemp failed, or a relative TMPDIR that is not a directory. On that path the signal traps are removed and the previous EXIT trap is restored
tmp_run_dir_cleanup 0 the run dir is gone (TMPDIR restored to the caller's original value, or unset if it was unset)
0 (also) nothing to do when TMP_RUN_DIR is empty

Caller-trap semantics (the part that is easy to get wrong)

  • An EXIT trap that already exists in this shell when tmp_run_dir_init runs is chained — ours first, then the caller's, with the original exit status visible to it and preserved afterwards.
  • INT/TERM/HUP traps are REPLACED, not chained.
  • On INT/TERM/HUP the EXIT trap in force at that moment runs (in a subshell, so an exit inside it cannot skip the re-raise) before the process re-raises the signal and dies by it. It does not exit 128+N, because bash only stops a for/while loop on Ctrl-C when the foreground child died of SIGINT.
  • A script that installs its own EXIT trap after init must call tmp_run_dir_cleanup from it.

Edge cases

  • A subshell's trap -p shows the parent's EXIT trap until the subshell sets a trap of its own. So the signal traps are installed before the EXIT trap is read, and the installing instance is recorded in _TMP_RUN_DIR_OWNER; both handlers refuse to act in any other shell instance. Without this, a subshell would chain — and later execute — a trap belonging to another shell.
  • set -e callers — the handlers switch errexit off for their own work and give the chained trap its exit status through if (exit N); then …; else …; fi (a condition is exempt from errexit), so a set -e caller still has its trap run on every non-zero exit and every signal.
  • A second signal during cleanup — further INT/TERM/HUP are ignored while the removal finishes synchronously, then the chain runs once (the pending chain is taken here). The interrupted outer handler never resumes because the process dies by the signal. A post-init caller trap interrupted by a second signal may run twice (S-8, tracked).
  • The run dir path is forgotten only after the removal finished, and the removal is retried three times, so a handler that interrupts mid-removal finds the path still set and finishes the job.
  • A relative TMPDIR is made absolute at init (or init fails loudly). A cleanup that cannot remove the run dir says so on stderr with safe_rm_rf's refusal reason — it is never silent.
  • POSIX mode — trap -p prints - for "no trap"; that is treated as no trap.
  • A foreign shell instance on the signal path sets trap - EXIT INT TERM HUP for itself and never touches the owner's run directory.
  • The signal cannot be re-raised (blocked or ignored, or no way to signal ourselves) — a diagnostic is printed and the process exits 128+N, explicitly noting that a parent shell will not see death by signal.
  • On the signal path the caller's trap runs in a subshell, so it sees variables but its own state changes do not reach the dying shell — an honest limit, stated in the header.

Internal behaviour

  1. A POSIX-only guard at the top rejects non-bash shells before any bash-only syntax is parsed.
  2. A re-source guard (_TMP_RUN_DIR_LOADED, deliberately not exported so a child loads its own copy).
  3. Sources safe_rm.sh from beside itself.
  4. tmp_run_dir_init normalises TMPDIR to an absolute directory, records the original, then installs the signal traps first, reads the EXIT trap this instance really owns, records the owner ($BASHPID, never $$ — inside ( … ), $( … ) or a pipeline stage $$ is the parent), installs _tmp_run_dir_exit, and finally allocates the directory with mktemp -d.
  5. _tmp_run_dir_exit acts only in the owner instance, cleans up, then runs the chained caller trap with the original status.
  6. _tmp_run_dir_on_signal blocks further signals, takes the pending chain, cleans up, removes the traps, runs the chain in a subshell, then re-raises the signal on $BASHPID.
  7. tmp_run_dir_cleanup restores TMPDIR to the absolute parent before removal (so safe_rm_rf accepts it), retries the removal, names a failure, then restores the caller's original TMPDIR.

Related scripts

  • scripts/lib/safe_rm.sh — the removal primitive (safe_rm_rf), and the reason TMPDIR is restored first.
  • scripts/lib/test_tmp_run_dir.sh — this library's suite (510 lines; it is what exercises the unset BASHPID path).
  • scripts/lib/test_user_bus_env.sh, scripts/lib/test_safe_rm.sh — sibling library suites.
  • Consumers: tests and scripts that create many temp directories, especially inside $(...).

Last verified

2026-12-04 — bash -n scripts/lib/tmp_run_dir.sh → exit 0 (a library: sourced, not executed).

Behaviour a reader can repeat (creates and removes one directory):

bash -c '. scripts/lib/tmp_run_dir.sh; tmp_run_dir_init "probe" || exit 2; \
  echo "dir=$TMP_RUN_DIR"; d=$(mktemp -d); echo "child=$d"; tmp_run_dir_cleanup; \
  [ -d "$TMP_RUN_DIR" ] && echo LEFT-BEHIND || echo removed; [ -d "$d" ] && echo child-left || echo child-gone'

Expected: dir=/tmp/probe.XXXXXX, child=/tmp/probe.XXXXXX/tmp.XXXXXX, then removed and child-gone.