Linux 下setitimer函数的使用

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

1. 要使用setitimer函数,要包含头文件:#include

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,其定义如下:

struct itimerval {
               struct timeval it_interval; /* next value */
               struct timeval it_value; /* current value */
           };

struct timeval {
               long tv_sec; /* seconds */
               long tv_usec; /* microseconds */
           };


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

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

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

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

#include     // for printf()  
#include  
#include 

#include 

void sigFunc()
{
   static int iCnt = 0;
   printf("The %d Times: Hello world\n", iCnt++);
}

int main(void)
{
   struct itimerval tv, otv;
   signal(SIGALRM, sigFunc);
   //how long to run the first time
   tv.it_value.tv_sec = 3;
   tv.it_value.tv_usec = 0;
   //after the first time, how long to run next time
   tv.it_interval.tv_sec = 1;
   tv.it_interval.tv_usec = 0;

   if (setitimer(ITIMER_REAL, &tv, &otv) != 0)
	printf("setitimer err %d\n", errno);

   while(1)
   {
	sleep(1);
	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);
   }
}



你可能感兴趣的:(Linux,编程,C/C++编程,Linux,编程)