Linux 下setitimer函数的使用

在编程的时候,很多时候会用到定时器,定时检测某个状态是否发生变化并进行处理。这时候,就会用到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,其定义如下:

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 <stdio.h>    // for printf()  
#include <signal.h> 
#include <sys/time.h>

#include <errno.h>

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);
   }
}



  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值