What are Unix signals
What you'll learn: You will understand how the operating system uses signals as a "tap on the shoulder" to notify your program of external events.
The Software "Interrupt"
Imagine you are deep in focus, reading a book. Suddenly, your phone pings with a notification. You stop reading, check the message, and then return to your book. In the world of systems programming, a signal is that notification.
Signals are limited, predefined messages sent by the Unix kernel to a process. They aren't complex data packets; they are more like a "shout" from across a room. They tell your program that something important has happened that requires immediate attention, forcing the program to pause its current task to handle the event.
Why do we need them?
Without signals, your program would be trapped in its own logic, unaware of the outside world. Signals allow for asynchronous communication—events that happen at unpredictable times. Common reasons a signal might be sent include:
- A user pressing
Ctrl+Cto stop the program (SIGINT). - The system detecting a math error, like dividing by zero (SIGFPE).
- Another process asking your program to shut down gracefully (SIGTERM).
- The program trying to access memory it doesn't own (SIGSEGV).
What happens when a signal hits?
Every signal has a "default action" defined by the operating system. Usually, this action is to terminate the program immediately. However, as a programmer, you can write your own "signal handler"—a function that runs specifically when a certain signal arrives.
Here is a conceptual look at how a program ignores the usual "quit" command to print a message instead:
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
// This function runs only when the signal is received
void handle_interruption(int sig) {
printf("\nCaught signal %d! I'm staying alive.\n", sig);
}
int main() {
// Register the handler for SIGINT (Ctrl+C)
signal(SIGINT, handle_interruption);
printf("Try pressing Ctrl+C. I'll wait...\n");
// Loop forever to keep the program running
while(1) {
sleep(1);
}
return 0;
}
In this example, the program doesn't "check" for the signal in the loop. The operating system forcibly interrupts the while loop, jumps to the handle_interruption function, and then returns to the loop once the function finishes.
Key takeaway
Unix signals are asynchronous notifications sent by the kernel to a process to trigger immediate, specific actions or error handling.