Handling alarms with alarm()
What you'll learn: How to use the alarm() function to schedule a "wake-up call" that interrupts your program after a specific amount of time.
The Software Egg Timer
Imagine you are boiling an egg while reading a book. If you don't set a timer, you might get lost in your chapters and forget the stove is on. In systems programming, alarm() acts as that kitchen timer.
When you call alarm(5), you are telling the Operating System: "Hey, let me go back to my work, but please poke me in exactly five seconds." When the time is up, the OS sends a SIGALRM signal to your process. By default, this signal will kill your program, but its real power comes when you pair it with a signal handler to trigger specific events.
Setting the Countdown
The alarm() function is simple: it takes one argument—an unsigned integer representing seconds. It does not pause your code; your program continues to run the very next line immediately.
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
void alarm_handler(int sig) {
printf("\n[BEEP BEEP] Time is up!\n");
}
int main() {
// Connect the SIGALRM signal to our handler function
signal(SIGALRM, alarm_handler);
printf("Setting an alarm for 3 seconds...\n");
alarm(3); // The timer starts ticking in the background
printf("The program continues to work while the timer runs.\n");
// We use pause() to wait specifically for a signal
pause();
printf("Program exiting gracefully.\n");
return 0;
}
Critical Rules of Alarms
There are two important things to remember about the alarm() function:
- One at a time: A process can only have one alarm active at a time. If you call
alarm(10)and then callalarm(5)two seconds later, the first alarm is canceled and replaced by the new 5-second timer. - Canceling: If you want to turn the timer off before it rings, you call
alarm(0).
This is incredibly useful for implementing "timeouts." For example, if you are waiting for a user to type a password and they take longer than 30 seconds, an alarm can trigger a function that automatically logs them out for security.
Key takeaway
The alarm() function schedules a SIGALRM signal to be delivered after a set number of seconds without blocking your program's execution.