0

无论 timer_handler 函数的执行时间如何,我想每 2 秒调用一次 timer_handler 函数这是我的代码

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

void timer_handler (int signum)
{
 static int count = 0;
 sleep(1);
 printf ("timer expired %d times %d signum \n", ++count, signum);
}

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

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

 /* Configure the timer to expire after 2000 msec... */
 timer.it_value.tv_sec = 2;
 timer.it_value.tv_usec = 0;
 /* ... and every 2000 msec after that. */
 timer.it_interval.tv_sec = 2;
 timer.it_interval.tv_usec = 0;
 /* Start a virtual timer. It counts down whenever this process is
   executing. */
 setitimer (ITIMER_VIRTUAL, &timer, NULL);
 /* Do busy work. */
 while (1);
}

根据上面的代码,它应该timer expired 1 times 26 signum每两秒打印一次,但它每 3 秒打印一次,其中包括睡眠时间,所以我想每 2 秒调用一次该函数。我不知道我在哪里做错了如果任何其他图书馆能够做到这一点,请告诉我谢谢

4

2 回答 2

2

为什么不使用挂钟时间?

这样做

  • 安装信号处理程序,SIGALRM而不是SIGVTALRM
  • 指定ITIMER_REAL而不是ITIMER_VIRTUAL.

无关但重要:信号处理程序只能调用异步信号安全函数。printf()不是其中之一。对于后者的列表,请单击此处并向下滚动

于 2017-12-28T13:36:19.387 回答
0

信号处理程序中的调用:sleep(1) 为信号处理增加了额外的时间。这额外的一秒不是进程执行时间的一部分。

从信号处理程序中删除:

sleep(1);

关于:

setitimer (ITIMER_VIRTUAL, &timer, NULL);

因为您想查看每 2 秒执行一次的信号处理程序,所以要使用的正确计时器是:ITIMER_REALnot ITIMER_VIRTUAL。这将导致测量“墙上的时钟”时间,而不是测量“进程运行”时间。

强烈建议让信号处理程序只设置一个标志。然后主函数中的“什么都不做”循环检查该标志,重置标志,然后调用 printf()`将锁定互斥锁,修改标志,然后解锁互斥锁。

于 2017-12-28T13:42:11.327 回答