Signal Handling and Process Control
Handles Unix signals in Bash scripts using trap, kill, and wait for graceful shutdown, timeout enforcement, and inter-process communication.
Code
#!/usr/bin/env bash
set -uo pipefail
on_sigterm() {
echo "Received SIGTERM, shutting down gracefully..."
exit 0
}
on_sigint() {
echo "Received SIGINT (Ctrl+C), cleaning up..."
exit 130
}
on_sigusr1() {
echo "Received SIGUSR1, reloading configuration..."
}
trap on_sigterm TERM
trap on_sigint INT
trap on_sigusr1 USR1
echo "PID: $$"
echo "Send signals: kill -TERM $$, kill -USR1 $$"
# Run a child process with timeout
run_with_timeout() {
local timeout=$1
shift
"$@" &
local pid=$!
(
sleep "$timeout"
kill -TERM "$pid" 2>/dev/null
) &
local timer_pid=$!
wait "$pid" 2>/dev/null
local status=$?
kill "$timer_pid" 2>/dev/null
wait "$timer_pid" 2>/dev/null
return $status
}
echo "Running with timeout..."
run_with_timeout 3 sleep 10 && echo "Completed" || echo "Timed out or failed"
# Graceful process termination
graceful_kill() {
local pid=$1
local timeout=5
kill -TERM "$pid" 2>/dev/null
for ((i=0; i<timeout*10; i++)); do
kill -0 "$pid" 2>/dev/null || return 0
sleep 0.1
done
echo "Process did not exit, sending SIGKILL"
kill -KILL "$pid" 2>/dev/null
}
echo "Signal handling demo complete"Report a problem with this exampleOpens a pre-filled issue on GitHub.