Linux 下setitimer函数的使用

来源:互联网 发布:美国大学统计 知乎 编辑:程序博客网 时间:2024/06/05 09:42

在编程的时候,很多时候会用到定时器,定时检测某个状态是否发生变化并进行处理。这时候,就会用到setitimer函数了。

1. 要使用setitimer函数,要包含头文件:#include <sys/time.h>

2. 该函数的原型是:int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value);

3. 参数:

(1)int which:为以下的一种

ITIMER_REAL:decrements in real time, and deliversSIGALRM upon expiration.

ITIMER_VIRTUAL:decrements only  when  the  process  is  executing,  anddeliversSIGVTALRM upon expiration.

ITIMER_PROF:decrements  both  when the process executes and when the system is executing on behalf 

of the  process. Coupledwith  ITIMER_VIRTUAL, this timer is usually used to profile the time

 spent by the application in user and  kernel space.  SIGPROF is delivered

(2)struct itimerval *new_value,其定义如下:

[cpp] view plain copy
  1. struct itimerval {  
  2.                struct timeval it_interval; /* next value */  
  3.                struct timeval it_value; /* current value */  
  4.            };  

[cpp] view plain copy
  1. struct timeval {  
  2.                long tv_sec; /* seconds */  
  3.                long tv_usec; /* microseconds */  
  4.            };  


其中it_value表示设置定时器后间隔多久开始执行定时任务,而it_interval表示两次定时任务之间的时间间隔。

(3)上一次定时器的值,一般置为NULL即可

4. 返回值:成功返回0;失败返回-1,并把错误号写到errno变量中

5. 以下是使用的简单实例(ITIMER_REAL,其他的类似)

[cpp] view plain copy
  1. #include <stdio.h>    // for printf()    
  2. #include <signal.h>   
  3. #include <sys/time.h>  
  4.   
  5. #include <errno.h>  
  6.   
  7. void sigFunc()  
  8. {  
  9.    static int iCnt = 0;  
  10.    printf("The %d Times: Hello world\n", iCnt++);  
  11. }  
  12.   
  13. int main(void)  
  14. {  
  15.    struct itimerval tv, otv;  
  16.    signal(SIGALRM, sigFunc);  
  17.    //how long to run the first time  
  18.    tv.it_value.tv_sec = 3;  
  19.    tv.it_value.tv_usec = 0;  
  20.    //after the first time, how long to run next time  
  21.    tv.it_interval.tv_sec = 1;  
  22.    tv.it_interval.tv_usec = 0;  
  23.   
  24.    if (setitimer(ITIMER_REAL, &tv, &otv) != 0)  
  25.     printf("setitimer err %d\n", errno);  
  26.   
  27.    while(1)  
  28.    {  
  29.     sleep(1);  
  30.     printf("otv: %d, %d, %d, %d\n", otv.it_value.tv_sec, otv.it_value.tv_usec, otv.it_interval.tv_sec, otv.it_interval.tv_sec);  
  31.    }  
  32. }  
原创粉丝点击