1.介绍
在linux下如果定时如果要求不太精确的话,使用alarm()和signal()就行了(精确到秒),但是如果想要实现精度较高的定时功能的话,就要使用setitimer函数。
setitimer()为Linux的API,并非C语言的Standard Library,setitimer()有两个功能,一是指定一段时间后,才执行某个function,二是每间隔一段时间就执行某个function, 以下程序demo如何使用setitimer()。
2.函数参数
1 int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue));2 3 struct itimerval {4 struct timeval it_interval;5 struct timeval it_value;6 };7 struct timeval {8 long tv_sec;9 long tv_usec;10 };
其中,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 timetick.it_value.tv_sec = 1;tick.it_value.tv_usec = 0;//After first, the Interval time for clocktick.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;}