如何在Linux下实现定时器

如何在Linux下实现定时器

 

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;

}

 

setitimeralarm有类似的功能,也是通过信号来实现)

 

最优雅的方法是使用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;

}

        

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值