In this lesson, you will learn how the Linux kernel injects asynchronous signals into your Bash processes to interrupt their execution flow.
The Signal Architecture
When you press Ctrl+C or send a command like kill -9, you aren't actually stopping a process directly. Instead, you are sending a signal—a small, numeric notification delivered by the Linux kernel.
Think of the kernel as a traffic controller. When an external event occurs (like a user interrupt), the kernel pauses your Bash script. Before the script resumes, the kernel inspects the process's Signal Mask—a bitmask indicating which signals the process is willing to acknowledge.
Asynchronous Interrupts at the C Level
Bash is written in C, and at that level, the process maintains a table of "Signal Handlers." When a signal arrives, the kernel forces the CPU to jump to a specific memory address: the address of the signal handler function.
If you have defined a trap in Bash (e.g., trap 'echo "Caught it!"' SIGINT), Bash has registered a internal C function to handle that specific signal number. Here is what happens under the hood when you hit Ctrl+C:
- Hardware Interrupt: Your keyboard controller sends an interrupt to the CPU.
- Kernel Processing: The kernel identifies the process associated with the current terminal and sends a
SIGINT(Signal 2) to your Bash process. - Context Switch: The kernel saves your script’s current state (the instruction pointer and stack) and forces the execution to the Bash C function responsible for executing your
trapcommand. - Resumption: Once your trap code finishes executing, the kernel restores the state, and your script continues exactly where it left off, or exits if the signal was fatal.
Why It Matters
This mechanism is entirely asynchronous. The script has no idea when the signal will arrive, which is why your cleanup routines (like deleting temporary files) must be registered globally via trap before the critical code runs. If you don't handle these signals, the kernel uses default behaviors, which usually result in an immediate, messy termination of your script.
Key Takeaway: Signal handling is a kernel-enforced interruption that forces your script to jump to a pre-defined handler, allowing you to intercept external events before the process is killed.