无论 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 秒调用一次该函数。我不知道我在哪里做错了如果任何其他图书馆能够做到这一点,请告诉我谢谢