In this lesson, you will learn how to design your scripts to gracefully handle and forward signals when they are managed by external process supervisors.
The Challenge of Signal Propagation
When you run a script inside a container or under a process manager (like systemd or supervisord), the manager often controls your script's lifecycle by sending signals. A common issue arises when your script spawns child processes: if the manager sends a SIGTERM to your script to shut it down, the script might terminate immediately, leaving "zombie" or orphaned child processes running in the background.
Signal Propagation Management ensures that when your main script receives a signal from the system, it doesn't just die—it acts as a responsible parent by passing that signal down to every process it has spawned.
Implementing Orchestrated Shutdowns
To handle this, we use the trap command to intercept the incoming signal. Instead of letting the script exit abruptly, we create a function that sends the signal to the process group.
#!/bin/bash
# Define a cleanup function to forward signals
cleanup() {
echo "Signal received, propagating to children..."
# Send SIGTERM to the entire process group of this script
kill -TERM -$$
exit 0
}
# Trap SIGTERM and SIGINT, calling the cleanup function
trap cleanup SIGTERM SIGINT
# Spawn a long-running child task
./background_task.sh &
# Wait for the child or signal
wait
How it Works
- The Trap: When the process manager sends a
SIGTERMto stop your script, thetrapcommand catches it before the script exits. - The Process Group (
-$$): In thekillcommand, the negative sign before$$(the current script's PID) tells Linux to target the entire process group. This ensures every child process spawned by your script receives the shutdown signal simultaneously. - Graceful Exit: By defining this behavior, you prevent resource leaks and ensure that the system environment remains clean, which is essential for stable service management.
This approach transforms your script from a simple execution block into a well-behaved service component that respects the lifecycle commands of your operating system.
Key Takeaway: To ensure clean shutdowns in managed environments, always trap exit signals and propagate them to your process group using kill -<SIGNAL> -$$.