linux的下两种定时器实现

定时器是比较常用的功能。一直很好奇底层的实现方法。我想最终是使用了CPU的硬件定时器中断机制。有两种实现方法,第一种精度较低,实际使用中并不多。

  • alarm方式

如果不要求很精确的话,用 alarm() 和 signal() 就够了

unsigned int alarm(unsigned int seconds)
专门为SIGALRM信号而设,在指定的时间seconds秒后,将向进程本身发送SIGALRM信号,又称为闹钟时间。进程调用alarm后,任何以前的alarm()调用都将无效。如果参数seconds为零,那么进程内将不再包含任何闹钟时间。如果调用alarm()前,进程中已经设置了闹钟时间,则返回上一个闹钟时间的剩余时间,否则返回0。参考示例如下:

 1 #include<iostream>
 2 #include<unistd.h>
 3 #include<signal.h>
 4 using namespace std;
 5 
 6 void signal_fun(int sig)
 7 {
 8         cout<<"alarm, sig="<<sig<<endl;
 9         alarm(2);
10         return;
11 }
12 
13 int main(void)
14 {
15         signal(SIGALRM, signal_fun);
16         alarm(2);
17 
18         while(1) pause();
19 
20         return 0;
21 }
  • settimer方式 

int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)); 

setitimer()比alarm功能强大,支持3种类型的定时器:

ITIMER_REAL : 以系统真实的时间来计算,它送出SIGALRM信号。
ITIMER_VIRTUAL : 以该行程真正有执行的时间来计算,它送出SIGVTALRM信号。
ITIMER_PROF : 以行程真正有执行及在核心中所费的时间来计算,它送出SIGPROF信号。
Setitimer()第一个参数which指定定时器类型(上面三种之一);第二个参数是结构itimerval的一个实例;第三个参数可不做处理。
Setitimer()调用成功返回0,否则返回-1。

参考示例如下:

 1 #include <stdio.h>
 2 #include <time.h>
 3 #include <sys/time.h>
 4 #include <stdlib.h>
 5 #include <signal.h>
 6 int count = 0;
 7 void set_timer()
 8 {
 9         struct itimerval itv, oldtv;
10         itv.it_interval.tv_sec = 5;
11         itv.it_interval.tv_usec = 0;
12         itv.it_value.tv_sec = 5;
13         itv.it_value.tv_usec = 0;
14 
15         setitimer(ITIMER_REAL, &itv, &oldtv);
16 }
17 
18 void sigalrm_handler(int sig)
19 {
20         count++;
21         printf("timer signal.. %d\n", count);
22 }
23 
24 int main()
25 {
26         printf("%d,%d,%d\n", SIGSEGV, SIGALRM, SIGRTMIN);
27         signal(SIGALRM, sigalrm_handler);
28         set_timer();
29         while (count < 1000)
30         {}
31         exit(0);
32 }

 

posted on 2013-01-27 21:08  小交响曲  阅读(603)  评论(0编辑  收藏  举报

导航