使用计时器每秒准确调用一个函数?

use*_*306 0 c signals timer

我需要每秒调用一个函数,因为我想根据每秒存储数据,所以我不能错过第二个?什么是C的最佳方法?

下面是timer_create方法的骨架,这个可靠吗?

#include <stdio.h>
#include <time.h>
#include <signal.h>

timer_t gTimerid;

void start_timer(void)
{        
  struct itimerspec value;

  value.it_value.tv_sec = 1;
  value.it_value.tv_nsec = 0;  
  value.it_interval.tv_sec = 1;
  value.it_interval.tv_nsec = 0;

  timer_create (CLOCK_REALTIME, NULL, &gTimerid);    
  timer_settime (gTimerid, 0, &value, NULL);
}

void stop_timer(void)
{        
  struct itimerspec value;

  value.it_value.tv_sec = 0;
  value.it_value.tv_nsec = 0;    
  value.it_interval.tv_sec = 0;
  value.it_interval.tv_nsec = 0;

  timer_settime (gTimerid, 0, &value, NULL);        
}

void timer_callback(int sig)
{    
  printf(" Catched timer signal: %d ... !!\n", sig);     
}

int main(int ac, char **av)
{
    (void) signal(SIGALRM, timer_callback);
    start_timer();
    while(1);
}
Run Code Online (Sandbox Code Playgroud)

R..*_*R.. 7

在Linux和其他POSIX系统上,timer_create是您正在寻找的功能.将定时器设置为通过信号传送,它将非常可靠.不要使用旧的ualarmsetitimerapis,这些旧的或api已被弃用并且有各种丑陋的问题你可能不想进入,除非你已经是实时unix东西的专家......