gpt4 book ai didi

c - 如何知道计时器是否已在 C 中结束

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:35 25 4
gpt4 key购买 nike

我需要能够同时启动多个计时器,并明确知道计时器是已停止还是仍在运行。

#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 结构 itimerspec *new_value, 结构 itimerspec * old_value):

By default, the initial expiration time specified in new_value->it_value is interpreted relative to the current time on the timer's clock at the time of the call. This can be modified by specifying TIMER_ABSTIME in flags, in which case new_value->it_value is interpreted as an absolute value as measured on the timer's clock; that is, the timer will expire when the clock value reaches the value specified by new_value->it_value. If the specified absolute time has already passed, then the timer expires immediately, and the overrun count (see timer_getoverrun(2)) will be set correctly.

最佳答案

I never break out of the loop. Why can't I get the overrun of the timer (it always returns 0, which means the timer has not passed its expiration)?

不,这意味着您没有超支。

即使您指定了实时信号,操作系统也不会对定时器信号进行排队。 Overun 告诉您如果木卡盘没有卡住信号,将会有多少信号排队。

假设您设置了一个每秒响一次的计时器。但是由于某种原因你没有处理信号。假设您将其阻塞了 5 秒钟。超限计数将为 4 - 您将/正在处理的信号和您错过的 4。

在您的情况下,您将一次性 计时器设置为在“超时”秒后关闭。信号发出了。将不再有信号,因此溢出始终为 0,因为它应该是。

关于c - 如何知道计时器是否已在 C 中结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19804071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com