Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

如何在Linux下实现定时器

Posted on 2009-03-13 15:39 Prayer 阅读(2107) 评论(0)  编辑 收藏 引用 所属分类: LINUX/UNIX/AIX
  在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;
}

 


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理