C.W.K.
Stream
Lesson 10 of 10 · published

Signals Deep Dive and watch

~10 min · signal, trap, watch

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The signals that matter most

  • SIGTERM (15) — "please exit." Default of kill.
  • SIGINT (2) — "the user pressed Ctrl+C."
  • SIGHUP (1) — "your terminal closed," or, by convention, "reload your config."
  • SIGKILL (9) — "die now." Cannot be caught.
  • SIGSTOP (17) / SIGCONT (19) — pause and resume. Like Ctrl+Z then fg.
  • SIGUSR1 / SIGUSR2 — application-defined. nginx uses USR1 for log rotation; Postgres uses USR1 for crash recovery.
  • SIGPIPE (13) — "the pipe you were writing to closed." The cause when commands die mid-pipeline.

Catching signals in scripts: trap

trap 'echo "caught Ctrl+C"; cleanup; exit 130' INT
trap 'rm -f /tmp/lock' EXIT
trap '' HUP            # ignore SIGHUP for this script

Trap on EXIT is the canonical pattern for cleanup — it runs regardless of how the script ends. We dig deeper in the scripting track.

watch — repeat a command

watch -n 1 'ls -lah | head' reruns every 1 second and displays the latest output, highlighting changes. Perfect for monitoring queue size, log line count, file growth. macOS doesn't ship watch — brew install watch.

watch flags

  • -n 5 — interval in seconds.
  • -d — highlight differences from the previous output.
  • -c — interpret ANSI colors in the output.
  • -x — execute command verbatim instead of via shell (needed for some quoting cases).

The minimum-viable monitor

watch -n 2 -d 'ls -lh /var/log/build.log'

Run during a long build. Size and timestamp tick; you know it's alive without flooding your screen with tail -f.

Code

trap pattern·bash
#!/usr/bin/env bash
set -euo pipefail
lock=/tmp/myjob.lock
trap 'rm -f "$lock"' EXIT INT TERM
echo $$ > "$lock"
# do work
sleep 30

External links

Exercise

Write a tiny script with a trap on EXIT that echoes 'cleanup'. Run it. Run again, Ctrl+C in the middle, see cleanup still runs. Then brew install watch; watch -n 2 -d 'ls -lh /tmp/'.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.