gpt4 book ai didi

c - 了解 struct itimerval 字段 tv_usec

转载 作者:太空狗 更新时间:2023-10-29 12:09:54 27 4
gpt4 key购买 nike

你好,我正在研究这段代码:

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>


volatile sig_atomic_t print_flag = true;
static int count = 0;

void timer_handler (int signum)
{

printf ("timer expired %d times\n", ++count);
if(count>20) {
print_flag = false;
}
}

int main ()
{
struct sigaction sa;
struct itimerval timer;

/* Install timer_handler as the signal handler for SIGVTALRM. */
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &timer_handler;
sigaction (SIGALRM, &sa, NULL);

/* Configure the timer to expire after 250 msec... */
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 250000;
/* ... and every 250 msec after that. */
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 250000;
/* Start a virtual timer. It counts down whenever this process is
executing. */
setitimer (ITIMER_REAL, &timer, NULL);

/* Do busy work. */
while (print_flag) {
sleep(1);
}

printf("job done bye bye\n");
exit(0);

}

有了这个设置,一切正常,我得到了这个输出

...
timer expired 17 times
timer expired 18 times
timer expired 19 times
timer expired 20 times
timer expired 21 times
job done bye bye

如果我尝试更改代码注释 timer.it_interval.tv_usectimer.it_interval.tv_usec 并同时设置 timer.it_value.tv_sectimer.it_value.tv_sec 等于,例如,3 它没有完成他的工作。

但是,如果我像这样维护 tv_usec 的显式声明,它会起作用:

 timer.it_value.tv_sec = 3;
timer.it_value.tv_usec = 0;
timer.it_interval.tv_sec = 3;
timer.it_interval.tv_usec = 0;

为什么我要为这两个字段明确声明 tv_usec

最佳答案

只要你不初始化 *.tv_usec字段,它们的值是未定义。如果它包含一个大于 999999 的值或小于 0 , setitimer ()只会失败 EINVAL如手册页所述。

您应该自己初始化所有数据。如果你愿意节省一行代码,你可以memset timer结构为 0与您为 sa 所做的方式相同.

关于c - 了解 struct itimerval 字段 tv_usec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064940/

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