Multiple alarms in C?
An answer to this question on Stack Overflow.
Question
This is probably a very basic question, but I'm using the code below to run a simple alarm. It works as I want it to, but I'm wondering if it's at all possible to run multiple alarms simultaneously that each trigger a different function when complete. Is there a way to do that?
#include <signal.h>
#include <sys/time.h>
#include <stdio.h>
#include <time.h>
void alarm_handler(int signum){
printf("five seconds passed!!\n");
}
int main(){
signal(SIGALRM, alarm_handler);
alarm(5);
pause();
return 0;
}
Answer
No. According to this source:
Alarm requests are not stacked; only one SIGALRM generation can be scheduled in this manner. If the SIGALRM signal has not yet been generated, the call shall result in rescheduling the time at which the SIGALRM signal is generated.
One alternative is to create a priority queue in which you put your tasks and then always schedule your alarm for the time difference between the current time and the task at the top of the queue.
But be sure to look at this SO question: you're limited in the kinds of things you can do inside your signal handler.