C语言 了解结构 itimerval 字段tv_usec



嗨,我正在研究这段代码:

#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 timesn", ++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 byen");
    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 结构,以0sa相同的方式。

相关内容

  • 没有找到相关文章

最新更新