SIGALRM is a signal in Unix-like operating systems that notifies a process when a timer set by the alarm()
function expires. This signal is typically used to implement timeouts, periodic tasks, or event-driven programming.
Here's a breakdown of how it works:
- The
alarm()
function: This function sets a timer for a specific duration. When the timer expires, the process receives a SIGALRM signal. - Signal Handling: The process can define a signal handler function to be executed when it receives the SIGALRM signal.
- Default Action: If the signal is not handled, the default action is to terminate the process.
Example:
Imagine you're writing a program that should run for a maximum of 10 seconds. You can use SIGALRM to implement this timeout:
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
void timeout_handler(int signum) {
printf("Timeout! Exiting...\n");
exit(1);
}
int main() {
// Set the timeout to 10 seconds
alarm(10);
// Set up the signal handler
signal(SIGALRM, timeout_handler);
// Perform some operation
// ...
return 0;
}
Practical Applications:
- Timeouts: Implementing timeouts in network connections or user interactions.
- Periodic Tasks: Scheduling regular events like log rotations, data backups, or sending reminders.
- Event-Driven Programming: Handling asynchronous events that occur after a specified time interval.
Important Considerations:
- Non-Preemptive: SIGALRM is not preemptive. It will only be delivered when the process is actively running.
- Signal Queue: Multiple SIGALRM signals might be queued if the process is busy.