了解结构 itimerval 字段 tv_usec

Understanding struct itimerval field 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 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,如手册页所述。

你应该自己初始化所有的数据。如果您愿意节省一行代码,您可以 memsettimer 结构 0sa.

相同的方式