Reputation: 248
Let's say I have some function func() in my program, and I need it to be called after some specific delay. So far I have googled it and ended up with folowing code:
#include <stdio.h>
#include <sys/time.h> /* for setitimer */
#include <unistd.h> /* for pause */
#include <signal.h> /* for signal */
void func()
{
printf("func() called\n");
}
bool startTimer(double seconds)
{
itimerval it_val;
double integer, fractional;
integer = (int)seconds;
fractional = seconds - integer;
it_val.it_value.tv_sec = integer;
it_val.it_value.tv_usec = fractional * 1000000;
it_val.it_interval = it_val.it_value;
if (setitimer(ITIMER_REAL, &it_val, NULL) == -1)
return false;
return true;
}
int main()
{
if (signal(SIGALRM, (void(*)(int))func) == SIG_ERR)
{
perror("Unable to catch SIGALRM");
exit(1);
}
startTimer(1.5);
while(1)
pause();
return 0;
}
And it works, but the problem is that settimer() causes func() to be called repeatedly with interval of 1.5 sec. And what I need, is to call func() just once. Can someone tell me how to do this? Maybe, I need some additional parameters to settimer() ?
Note: time interval should be precise, because this program will play midi music later.
Upvotes: 1
Views: 3319
Reputation: 20862
Unless you need the program to be doing other things, you can simply sleep for the time allotted.
If you need to use the alarm, you can install the alarm to be processed once.
From the man page:
struct timeval it_interval
This is the period between successive timer interrupts. If zero, the alarm will only be sent once.
Instead of your code:
it_val.it_interval = it_val.it_value;
I'd set:
it_val.it_interval.tv_sec = 0;
it_val.it_interval.tv_usec = 0;
In addition to it_val.it_value which you already set. What you've done is use the same values for both structures, and that is why you see a repeated interval.
Upvotes: 3