Sub topic 7
Timeouts and exit codes: knowing when a run failed
This chapter assumes you can write short shell scripts, know that every process returns an exit status, and have already seen how a headless agent is started. Here you learn how to decide whether a scheduled run succeeded, hung, or failed, and how to report that decision to the scheduler.
Why an unattended run needs a definition of failure
In an interactive session, you notice when the agent stalls or produces nonsense. In a scheduled job, nobody is watching. The only signals are the exit status, the log, and whatever the scheduler does with them.
Two failure modes need handling:
- The run never ends. The agent waits on a network call, loops on a task, or blocks on a prompt that nobody can answer. Without a limit, it holds a lock, uses quota, and blocks the next run.
- The run ends badly but quietly. The process exits, but nobody checks how. The scheduler reports success because your script ended with a harmless command.
A timeout handles the first mode. Careful exit-status handling handles the second.
Exit codes you will meet
An exit status is an integer from 0 to 255. By convention, 0 means success and anything else means failure. Beyond that, meanings depend on the program. The table lists values you will see around timeout and shells.
| Status | Meaning |
|---|---|
| 0 | The command reported success. |
| 1, 2, and other small values | Defined by the program. Check your agent's documentation. |
| 124 | `timeout` stopped the command because the time limit expired. |
| 125 | `timeout` itself failed, for example because of a bad option. |
| 126 | The command was found but could not be run, often a permissions problem. |
| 127 | The command was not found, often a `PATH` problem under cron. |
| 137 | The process was killed by SIGKILL (128 + 9). |
| 143 | The process was terminated by SIGTERM (128 + 15). |
Statuses above 128 mean the process died from a signal. The signal number is the status minus 128.
Statuses 125 to 127 usually point to a setup mistake, not an agent failure. If a job that worked in your shell returns 127 under the scheduler, the cause is almost always the environment. The earlier chapter on scheduler environments covers that case.
Setting a timeout with `timeout`
The GNU timeout command runs another command and stops it after a duration:
timeout 20m $AGENT_CMD < prompts/nightly.mdWhen the time is up, timeout sends SIGTERM and exits with status 124. SIGTERM asks the process to stop, and a stuck process can ignore it. Add --kill-after to follow with SIGKILL, which cannot be ignored:
timeout --kill-after=30s 20m $AGENT_CMD < prompts/nightly.mdThis gives the agent 20 minutes, then a 30-second grace period to clean up. If SIGTERM is enough, the status is 124. If SIGKILL was needed, the status is 137, not 124. Your handling code should treat both as a timeout.
On macOS, timeout is not installed by default. The GNU version is available as gtimeout from the coreutils package, so check which one your host has.
Two edge cases matter:
- Child processes. An agent may start helpers such as test runners, language servers, or shells. Signals sent to the agent do not always reach those helpers. After a timeout, check that no stray processes remain, and test this once before you rely on it.
--preserve-status. This option makestimeoutreturn the command's own status instead of 124. That hides the timeout from your script, so avoid it unless you have a reason.
Layering limits
Each scheduler has its own time limit, and the limits stack. In the examples from this tutorial, the wrapper uses timeout 20m, the systemd service has TimeoutStartSec=30min, and the CI job has timeout-minutes: 30.
Set the innermost limit shortest. If the wrapper times out first, it can write a clear message to the log and exit with a known status. If the outer limit fires first, the scheduler kills the whole job abruptly, and your cleanup and logging code never runs.
An exit status of 0 is not proof of success
The agent's exit status says whether the process ended normally. It does not say whether the work was done. Many agents exit 0 after they say they could not finish a task. Status values also differ between agents, so read the documentation for yours before you map them.
Treat the exit status as a necessary check, not a sufficient one. When the agent produces a result file, validate it before any later step acts on it:
# Fail the job if the agent's result file is not the shape we asked for.
if ! jq -e '.status == "ok" and (.changed_files | type == "array")' result.json > /dev/null; then
echo "result.json is missing or malformed" >&2
exit 1
fijq -e sets its exit status from the last output value. It exits 0 when the expression gives a value other than false or null, and 1 otherwise. A missing file also produces a non-zero status. Requesting and validating structured output gets its own chapter later.
Getting the status to the scheduler
A wrapper script is the layer between the scheduler and the agent. Its last job is to pass the right status upward. Each scheduler reacts differently:
- cron ignores the exit status. It only emails any output, if mail is set up. You must write your own alerting.
- systemd marks the service as
failedwhen the script exits non-zero, andsystemctl statusandjournalctlshow it. - CI marks the job red, and can notify through its normal channels.
The wrapper
This script, from the earlier chapters, shows the pieces together. This chapter adds the --kill-after option and a status check that separates a timeout from other failures.
#!/usr/bin/env bash
# nightly-agent.sh
# AGENT_CMD is a placeholder for your agent's non-interactive command.
# This script assumes it reads the prompt from stdin; check your agent's documentation.
set -u
: "${AGENT_CMD:?set AGENT_CMD to your agent's non-interactive command}"
LOG_DIR="$HOME/agent-logs"
mkdir -p "$LOG_DIR"
LOG="$LOG_DIR/nightly-$(date -u +%Y%m%dT%H%M%SZ).log"
# Skip this run if the previous one is still active.
exec 9>"$HOME/.nightly-agent.lock"
if ! flock -n 9; then
echo "previous run still active, skipping" >> "$LOG_DIR/skipped.log"
exit 0
fi
cd /srv/repos/my-project || exit 1
# AGENT_CMD is intentionally unquoted so a command with arguments splits into words.
timeout --kill-after=30s 20m $AGENT_CMD < prompts/nightly.md > "$LOG" 2>&1
status=$?
case "$status" in
0)
;;
124|137)
echo "agent timed out after 20 minutes (status $status)" >> "$LOG"
echo "nightly agent timed out, log: $LOG" >&2
;;
125|126|127)
echo "agent could not be started (status $status), check PATH and AGENT_CMD" >> "$LOG"
echo "nightly agent did not start, log: $LOG" >&2
;;
*)
echo "nightly agent failed with status $status, log: $LOG" >&2
;;
esac
exit "$status"Points to notice:
status=$?comes right after thetimeoutline. Any command in between would overwrite$?.- The script does not use
set -e. With it, the script would stop at the failing line before yourcaseblock could classify the status. Capturing the status yourself is clearer here. - The final
exit "$status"passes the agent's status on unchanged. Without it, the script would exit with the status of the last command run, which might be a successfulecho. - The skip path exits 0 on purpose, because an overlapping run is not an error. This means a skip is invisible to the scheduler. The
skipped.logfile and your alerting must catch the case where skips repeat for days.
Pipelines hide failures
A common mistake is piping agent output through tee to see it live and keep a log:
timeout 20m $AGENT_CMD < prompts/nightly.md 2>&1 | tee "$LOG"
echo "status: $?" # this is the status of tee, not the agentBy default, a pipeline returns the status of its last command. Here that is tee, which almost always succeeds. Use set -o pipefail so the pipeline fails if any stage fails, or read the PIPESTATUS array right after the pipeline:
timeout 20m $AGENT_CMD < prompts/nightly.md 2>&1 | tee "$LOG"
status=${PIPESTATUS[0]}The decision flow
The diagram shows how the wrapper classifies a run and what each outcome sends to the scheduler.
Common mistakes
- No timeout at all. One hung run then blocks every later run if you use a lock.
- Ending the script with an unrelated command. The script then reports that command's status, not the agent's.
- Treating 124 as a generic failure. A timeout often calls for a different response than a crash, such as a smaller task or a longer limit.
- Assuming exit 0 means the task was done. Validate the output.
- Interactive prompts. An agent that stops to ask for approval will wait until the timeout fires. If your jobs often hit the limit with an empty log, check for a blocked prompt, which is a permissions problem covered in an earlier chapter.
Exercise
A wrapper runs timeout --kill-after=30s 20m $AGENT_CMD. One night, the agent ignores SIGTERM and has to be killed. What exit status does timeout return, and which cases in your handling code must cover it?
Show answer
It returns 137 (128 + 9, SIGKILL) instead of 124. The handling code must treat both 124 and 137 as a timeout, for example with a 124|137) case branch.
Exercise
A script runs timeout 20m $AGENT_CMD 2>&1 | tee "$LOG" and then exit $?. The agent crashes with status 1, but the scheduler shows the job as successful. Why, and how do you fix it?
Show answer
In a pipeline without pipefail, $? holds the status of the last command, tee, which succeeded. Fix it by enabling set -o pipefail before the pipeline, or by reading ${PIPESTATUS[0]} immediately after it and exiting with that value.
Exercise
Why should the wrapper's timeout be shorter than the scheduler's own time limit, such as systemd's TimeoutStartSec or the CI timeout-minutes?
Show answer
If the wrapper's limit fires first, the script keeps control. It can log the timeout and exit with a known status. If the scheduler's limit fires first, it kills the whole job at once, so the script's logging and cleanup never run.