【发布时间】:2013-11-06 04:22:19
【问题描述】:
我需要能够同时启动多个计时器,并明确知道计时器是否已停止或仍在运行。
#define RESEND_TIMEOUT 5
void timerCreate();
void timer_start(timer_t * timer, uint32 timeout);
bool timer_complete(timer_t * timer);
int main() {
timer_t resend_timer = timerCreate();
timer_start(&resend_timer, RESEND_TIMEOUT);
while(1) {
if (timer_complete(&resend_timer))
break;
}
}
void timer_start(timer_t * timer, uint32_t timeout)
{
printf("timer starting\n");
struct itimerspec it_val;
it_val.it_value.tv_sec = timeout;
it_val.it_value.tv_nsec = 0;
// timer expires once
it_val.it_interval.tv_sec = 0;
it_val.it_interval.tv_nsec = 0;
if (timer_settime(*timer, 0, &it_val, NULL) == -1) {
errExit("Could not set timeout");
}
}
// return true if timer ended
bool timer_complete(timer_t * timer)
{
if(timer_getoverrun(*timer) == 0)
return false;
else
return true;
}
我从不跳出循环。为什么我不能得到定时器的溢出(它总是返回0,这意味着定时器还没有过期)?然而,当我添加一个信号处理程序时,我知道计时器到期了。
我想在 timer_complete 函数中尝试 timer_gettime(timer_t timerid, struct itimerspec *curr_value) 以查看剩余时间是否为 0,但是如何在没有全局变量的情况下传递 curr_value 参数?
最后但并非最不重要的一点是,在使用 timer_settime 武装计时器时,我尝试使用 TIMER_ABSTIME 标志。从 int timer_settime(timer_t timerid, int flags, const struct itimerspec *new_value, struct itimerspec * old_value):
默认情况下,指定的初始过期时间 new_value->it_value 相对于当前时间解释 呼叫时计时器的时钟。这可以通过修改 在标志中指定 TIMER_ABSTIME,在这种情况下为 new_value->it_value 被解释为在定时器时钟上测量的绝对值; 即当时钟值达到该值时,定时器将超时 由 new_value->it_value 指定。如果指定的绝对时间有 已经过去了,那么计时器立即到期,并且超限 计数(参见 timer_getoverrun(2))将被正确设置。
【问题讨论】:
-
也许你想要timerfd_create(2) 和poll(2)