Linux定时器函数setitimer

来源:互联网 发布:氪星网络 编辑:程序博客网 时间:2024/05/16 07:33

1.介绍

  在linux下如果定时如果要求不太精确的话,使用alarm()和signal()就行了(精确到秒),但是如果想要实现精度较高的定时功能的话,就要使用setitimer函数。

  setitimer()为Linux的API,并非C语言的Standard Library,setitimer()有两个功能,一是指定一段时间后,才执行某个function,二是每间格一段时间就执行某个function, 以下程序demo如何使用setitimer()。

2.函数参数

int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue));  struct itimerval {  struct timeval it_interval;  struct timeval it_value;  };  struct timeval {  long tv_sec;  long tv_usec;  };

其中,which为定时器类型,3中类型定时器如下:

  ITIMER_REAL : 以系统真实的时间来计算,它送出SIGALRM信号。  

  ITIMER_VIRTUAL : -以该进程在用户态下花费的时间来计算,它送出SIGVTALRM信号。  

  ITIMER_PROF : 以该进程在用户态下和内核态下所费的时间来计算,它送出SIGPROF信号。

  第二个参数指定间隔时间,第三个参数用来返回上一次定时器的间隔时间,如果不关心该值可设为NULL。

  it_interval指定间隔时间,it_value指定初始定时时间。如果只指定it_value,就是实现一次定时;如果同时指定 it_interval,则超时后,系统会重新初始化it_value为it_interval,实现重复定时;两者都清零,则会清除定时器。  

  tv_sec提供秒级精度,tv_usec提供微秒级精度,以值大的为先,注意1s = 1000000us。 

  如果是以setitimer提供的定时器来休眠,只需阻塞等待定时器信号就可以了。

  setitimer()调用成功返回0,否则返回-1。

3.范例

  该示例程序每隔1s产生一行标准输出。

#include <stdio.h>        //printf()#include <unistd.h>        //pause()#include <signal.h>        //signal()#include <string.h>        //memset()#include <sys/time.h>    //struct itimerval, setitimer()static int count = 0;void printMes(int signo){    printf("Get a SIGALRM, %d counts!\n", ++count);}int main(){    int res = 0;    struct itimerval tick;    signal(SIGALRM, printMes);    memset(&tick, 0, sizeof(tick));    //Timeout to run first time    tick.it_value.tv_sec = 1;    tick.it_value.tv_usec = 0;    //After first, the Interval time for clock    tick.it_interval.tv_sec = 1;    tick.it_interval.tv_usec = 0;    if(setitimer(ITIMER_REAL, &tick, NULL) < 0)            printf("Set timer failed!\n");    //When get a SIGALRM, the main process will enter another loop for pause()    while(1)    {        pause();    }    return 0;}
原创粉丝点击