Basic signal handling with signal()
What you'll learn: How to use the signal() function to intercept and respond to specific software interrupts sent by the operating system.
The Software Tap on the Shoulder
Imagine you are deeply engrossed in reading a book. Suddenly, your phone buzzes. This is an interrupt. You stop reading, handle the notification (the "event"), and then decide whether to go back to your book or stop reading entirely.
In Linux and Unix systems, signals are these interrupts. They are short messages sent to a running program to tell it something happened—like the user pressing Ctrl+C to quit, or a hardware error occurring. By default, most signals simply kill your program. However, you can write a "handler" to catch these signals and react gracefully.
Writing a Signal Handler
A signal handler is just a regular C function that takes one integer as an argument (the signal number). You tell the operating system to use your function instead of the default behavior by using the signal() function from the <signal.h> library.
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
// This is our handler function
void handle_sigint(int sig) {
printf("\nCaught signal %d! Saving data before exiting...\n", sig);
}
int main() {
// Register the handler for SIGINT (Ctrl+C)
// "When SIGINT happens, run handle_sigint"
signal(SIGINT, handle_sigint);
printf("Program running. Press Ctrl+C to test the handler.\n");
while(1) {
printf("Working...\n");
sleep(2);
}
return 0;
}
How it works
- The Signal:
SIGINTis the signal sent when a user interrupts a process (usually viaCtrl+C). - The Registration: By calling
signal(SIGINT, handle_sigint), you are telling the kernel: "If you send me aSIGINT, don't kill me immediately. Instead, pause my execution and jump to thehandle_sigintfunction." - The Execution: The main loop runs indefinitely. When you press
Ctrl+C, the loop pauses, the message prints, and then (because we didn't callexit()), the program jumps right back into the loop.
This is the foundation of building robust systems programs that don't just crash, but instead clean up temporary files or close database connections when they are told to stop.
Key takeaway
The signal() function allows you to redirect system interrupts to custom functions, giving your program a chance to respond to events rather than simply being terminated.