All writing

A Bash watchdog trap waits for the foreground command

While hardening a wrapper script around git hooks, I ran into two Bash signal behaviours that I didn’t know about. Both are in the Bash manual, which I only found out after they’d already broken the wrapper, so I wrote them down with small scripts that show them, which we can run to see both for ourselves.

The wrapper runs each pre-commit hook with a wall-clock hang bound, so a hook that hangs gets stopped and reported instead of leaving git commit sitting there forever, and it forwards Ctrl-C to the hook so we can cancel a commit. The bound is a tiny watchdog process that sleeps until a deadline and then sends the wrapper SIGALRM, and the wrapper has a trap on ALRM that stops the hook’s process group and exits with 124. Before a hook can run, the wrapper sometimes has to prepare things, and one of those things is building a command-line tool the hook needs, which can take a while and could also hang.

The trap runs when the command is done

The script below gets an ALRM from its watchdog after one second, while it’s busy with a four-second command:

#!/bin/bash
start=$SECONDS
trap 'echo "trap ran after $((SECONDS - start))s"' ALRM
( sleep 1; kill -ALRM $$ ) &
case "$1" in
  fg)    sleep 4 ;;
  subst) x=$(sleep 4) ;;
  wait)  sleep 4 & wait $! ;;
  *)     kill $!; echo "usage: $0 fg|subst|wait" >&2; exit 2 ;;
esac
echo "done after $((SECONDS - start))s"

(The last arm kills the watchdog, so a typo doesn’t leave it sending ALRM to a pid that might belong to something else by then.) The output is the same on macOS’s /bin/bash 3.2 and on Bash 5.3 from Homebrew, give or take a second, since $SECONDS only counts whole seconds:

$ bash alrm.sh fg
trap ran after 4s
done after 4s
$ bash alrm.sh subst
trap ran after 4s
done after 4s
$ bash alrm.sh wait
trap ran after 1s
done after 1s

The signal arrives at one second in all three cases, but in the first two the trap only runs once sleep returns. The manual says as much: if Bash is waiting for a command to complete and gets a signal it has a trap for, the trap doesn’t run until the command completes, but when it’s waiting through the wait builtin, wait returns at once with a status above 128 and the trap runs right after. A command substitution counts as a foreground command too, which is the case that mattered here, because the wrapper built the tool with something like path=$(build_the_tool).

So a watchdog that ALRMs a script can only act between commands or inside wait, and a foreground command holds it off for as long as that command runs, which for a hung build is forever. (My first plan, starting the clock earlier, wouldn’t have changed that at all.) The fix is to run the slow thing as a background job and wait on it, keeping its pid where the trap can find it:

build_the_tool >"$out" &
pipeline_pid=$!
wait "$pipeline_pid"
pipeline_pid=""

Note that wait returning doesn’t stop the job, it keeps running happily in the background, so the trap has to do the stopping itself. In the wrapper the job is started in a process group of its own, and the trap sends TERM to the whole group, gives it a grace period, and then KILLs whatever is left, so a build’s child processes go down with it too (unless one of them moves itself into a new group or session).

An alarm that lands before the launch

A run on a heavily loaded machine still let a hung build run well past its bound. The alarm had landed earlier than expected, during an ordinary foreground command that runs before the build (a file listing), and when the trap finally ran after that command returned, there was no pipeline pid set yet, so the handler decided the hook had already finished and returned. It was answering “is the hook still running?” when the question it needed was “has the hook been launched?”, so the wrapper got a second flag, and any alarm that arrives before the launch now counts as an expired bound.

Setting that flag is where it’s easy to go wrong. Bash runs a pending trap between commands, and my first version set the flag in the same command as the pid, pipeline_pid=$! hook_launched=true, right after the &. That keeps the two assignments together, but a trap can still run between the & command and that one, when the job already exists and the flag still says it doesn’t, and then the handler exits as if nothing was running and leaves the job behind. A loop that sends the alarm right as the job starts hit that window about once in every one or two hundred runs, on both Bash versions.

What closes the gap is that $! changes inside the & command itself, so the trap can look at it. We mark the launch before it happens, remember what $! was, and let the trap pick up the job if $! has moved on:

expire_hang_bound() {
	if [[ "$launching" == true && "$hook_launched" != true && "$!" != "$before_launch" ]]; then
		# The alarm fell between the & and the assignment below: the job exists and $! names it.
		pipeline_pid=$! hook_launched=true
	fi
	if [[ "$hook_launched" == true ]]; then
		# It fired as the pipeline finished: the hook made its bound.
		[[ -n "$pipeline_pid" ]] && kill -0 "$pipeline_pid" 2>/dev/null || return 0
	fi
	# Before or during the hook: stop the group if there is one, report, exit 124.
}
trap expire_hang_bound ALRM

launching=true before_launch=$!
run_the_hook &
pipeline_pid=$! hook_launched=true
wait "$pipeline_pid"
pipeline_pid=""

An alarm before the & sees $! unchanged and stops the run before the hook starts, and an alarm after it finds the job either through pipeline_pid or through $!. With the same stress loop, the trap now picked the job up through $! 15 times in 1,600 runs, and every one of those runs ended with the job known and stopped.

Rule: a trap can’t trust a flag that the main script sets after the thing it describes, so give it something Bash itself updates at the same moment, like $!.

To test this kind of thing, it helped to slow one command down instead of the hook. A stub that sleeps a couple of seconds before calling the real mktemp, or the interpreter behind the listing, with a one-second bound, puts the alarm before the launch on purpose, and the tests check that the hook never ran and what the report says, not just the exit code.

Ctrl-C never reached the hook

The second behaviour was separate. In the script below the child installs an INT trap, writes a file to say it’s ready, and the parent only sends INT after that file shows up, so timing can’t explain the result:

#!/bin/bash
ready=$(mktemp -u)
bash -c 'trap "echo child got INT; exit 130" INT; touch "$1"; sleep 3 & wait $!; echo child finished normally' _ "$ready" &
child=$!
until [ -e "$ready" ]; do sleep 0.1; done
kill -INT $child
wait $child; echo "child exit: $?"
rm -f "$ready"
$ bash int.sh
child finished normally
child exit: 0

The child has a trap on INT, it gets sent INT after the trap is set, and it doesn’t care. Two things from the manual combine here. When job control is off, which it is in a script by default, a command started with & ignores SIGINT and SIGQUIT. And a signal that was ignored when a non-interactive shell started can’t be trapped or reset by that shell, so the child’s trap ... INT is a silent no-op (and a program that isn’t Bash inherits the ignored signal the same way). So in the wrapper, forwarding Ctrl-C to the hook’s process group reached no process that would act on it.

The child can’t fix this for itself, but whoever starts it can. One way is to put the default handlers back before execing the real command, with a one-line Perl shim:

#!/bin/bash
ready=$(mktemp -u)
perl -e '$SIG{INT} = "DEFAULT"; $SIG{QUIT} = "DEFAULT"; exec @ARGV' \
  bash -c 'trap "echo child got INT; exit 130" INT; touch "$1"; sleep 3 & wait $!; echo child finished normally' _ "$ready" &
child=$!
until [ -e "$ready" ]; do sleep 0.1; done
kill -INT $child
wait $child; echo "child exit: $?"
rm -f "$ready"
$ bash int-fixed.sh
child got INT
child exit: 130

The child runs its sleep as a background job and waits on it for the same reason as in the first section, otherwise its own trap would wait out the three seconds before printing. The other way is set -m at the top of the parent script, which turns job control on, so & jobs keep the default INT and QUIT and also get a process group of their own. The wrapper uses the shim, with a setpgrp(0, 0) before the exec to give each job its own group, and every launch needs it, the build job included, since that’s a background job like any other.

Summary

If a Bash script is meant to react to a signal while something slow runs, the slow thing has to be a background job the script waits on, because a trap waits for a foreground command (a $(...) included) to return before it runs, and since wait returns without stopping the job, a trap that doesn’t exit has to stop it or wait again. What the trap reads to decide what happened has to stay right at every point a trap can run, which is between any two commands, so it’s safer to read $! than a flag set after the launch. And without job control, jobs we background from a script start with INT and QUIT ignored and nothing inside them can undo that, so to forward Ctrl-C we either restore the handlers before the exec or turn job control on with set -m.

Email address copied [email protected]