假设我的程序中有一些函数 func(),我需要在特定延迟后调用它。到目前为止,我已经用谷歌搜索并最终得到以下代码:
#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;
}
它可以工作,但问题是 settimer() 导致 func() 以 1.5 秒的间隔重复调用。而我需要的是只调用 func() 一次。 有人可以告诉我该怎么做吗?也许,我需要一些额外的参数来 settimer() ?
注意:时间间隔要准确,因为这个程序稍后会播放midi音乐。
最佳答案
除非您需要程序做其他事情,否则您可以在分配的时间内简单地休眠。
如果需要使用报警器,可以安装报警器一次处理。
来自手册页:
struct timeval it_interval
This is the period between successive timer interrupts. If zero, the alarm will only be sent once.
代替您的代码:
it_val.it_interval = it_val.it_value;
我会设置:
it_val.it_interval.tv_sec = 0;
it_val.it_interval.tv_usec = 0;
除了您已经设置的 it_val.it_value。您所做的是对两个结构使用相同的值,这就是您看到重复间隔的原因。
关于c++ - linux c++ 如何在特定时间间隔后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26077080/