【发布时间】:2018-06-09 01:02:21
【问题描述】:
我想每隔 2 秒调用一次 timer_handler 函数,而不管 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 秒调用一次该函数。
我不知道我在哪里做错了
如果任何其他图书馆能够做到这一点,请告诉我
谢谢
【问题讨论】:
-
在信号处理程序中使用不安全的函数有一长串,
sleep()和printf()都在该列表中。 -
删除
sleep()怎么样?你的最终目标是什么?我的意思是while (1)很浪费。 -
@user3629249: As per POSIX
sleep()应该是异步信号安全的。 -
@alk,这里是
sleep()的MAN页面的摘录┌──────────┬───────────── ┬────────────────────────────┐ │接口│属性│值│├──────────┼ ────────────────┼──────────────────────────────┤ │sleep() │ 线程安全 │ MT-Unsafe sig:SIGCHLD/linux │ └──────────┴──────────────┴────────── ────────────────────┘ 注意“Unsafe sig:SIGCHLD/linux”部分 -
@user3629249: 这个手册页你引用的是哪个 C 实现的文件?