在Linux实现一个定时器,不像Win32下那样直观。在Win32调用SetTimer就行了,在Linux下则没有相应函数可以直接调用。定时器作为一个常用的功能,在Linux当然也有相应实现。下面我们看看几种常用的方法。
要实现定时器功能,最土的办法实现莫过于用sleep/usleep来实现了。当然,它会阻塞当前线程,除了处理定时功能外,什么活也干不了。当然要解决这个问题不难,创建一个单独的线程来负责定时器,其它线程负责正常的任务就行了。
要实现定时器功能,最简单的办法就是ALARM信号。这种方法简单,也相应的缺陷:用信号实现效率较低; 最小精度为1秒,无法实现高精度的定义器。简单示例: #include <stdio.h> #include <signal.h>
static void timer(int sig) { if(sig == SIGALRM) { printf("timer\n"); }
return; }
int main(int argc, char* argv[]) { signal(SIGALRM, timer);
alarm(1);
getchar();
return 0; }
(setitimer和alarm有类似的功能,也是通过信号来实现)
最优雅的方法是使用RTC机制。利用select函数,你可以用单线程实现定时器,同时还可以处理其它任务。简单示例:
#include <stdio.h> #include <linux/rtc.h> #include <sys/ioctl.h> #include <sys/time.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <errno.h>
int main(int argc, char* argv[]) { unsigned long i = 0; unsigned long data = 0; int retval = 0; int fd = open ("/dev/rtc", O_RDONLY);
if(fd < 0) { perror("open"); exit(errno); }
/*Set the freq as 4Hz*/ if(ioctl(fd, RTC_IRQP_SET, 4) < 0) { perror("ioctl(RTC_IRQP_SET)"); close(fd); exit(errno); } /*Set the freq as 4Hz*/ if(ioctl(fd, RTC_IRQP_SET, 4) < 0) { perror("ioctl(RTC_IRQP_SET)"); close(fd); exit(errno); }
/* Enable periodic interrupts */ if(ioctl(fd, RTC_PIE_ON, 0) < 0) { perror("ioctl(RTC_PIE_ON)"); close(fd); exit(errno); }
for(i = 0; i < 100; i++) { if(read(fd, &data, sizeof(unsigned long)) < 0) { perror("read"); close(fd); exit(errno); } printf("timer\n"); } /* Disable periodic interrupts */ ioctl(fd, RTC_PIE_OFF, 0); close(fd);
return 0; }********************************************************************************** 调用setitimer安装定时器: 它有三个参数第一个设ITIMER_REAL,第二和三个参数是新的时钟间隔和之前设置的时钟间隔。 struct itimerval { struct timeval it_interval; //设为时钟间隔 struct timeval it_value; //设为第一次触发的时钟间隔,其实只被执行一次,以后按照it_interval的值 } 下面是一个具体的例子 #include <stdio.h> |
|