欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

Linux下实现定时器Timer的几种方法总结

程序员文章站 2022-06-10 16:48:31
定时器timer应用场景非常广泛,在linux下,有以下几种方法: 1,使用sleep()和usleep() 其中sleep精度是1秒,usleep精度是1微妙,具体代...

定时器timer应用场景非常广泛,在linux下,有以下几种方法:

1,使用sleep()和usleep()

其中sleep精度是1秒,usleep精度是1微妙,具体代码就不写了。使用这种方法缺点比较明显,在linux系统中,sleep类函数不能保证精度,尤其在系统负载比较大时,sleep一般都会有超时现象。

2,使用信号量sigalrm + alarm()

这种方式的精度能达到1秒,其中利用了*nix系统的信号量机制,首先注册信号量sigalrm处理函数,调用alarm(),设置定时长度,代码如下:

#include <stdio.h>
#include <signal.h>

void timer(int sig)
{
    if(sigalrm == sig)
    {
        printf("timer\n");
        alarm(1);    //we contimue set the timer
    }

    return ;
}

int main()
{
    signal(sigalrm, timer); //relate the signal and function

    alarm(1);    //trigger the timer

    getchar();

    return 0;
}

alarm方式虽然很好,但是无法首先低于1秒的精度。

3,使用rtc机制

rtc机制利用系统硬件提供的real time clock机制,通过读取rtc硬件/dev/rtc,通过ioctl()设置rtc频率,代码如下:

#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>
#include <stdlib.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, 1) < 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;
}

这种方式比较方便,利用了系统硬件提供的rtc,精度可调,而且非常高。

4,使用select()

这种方法在看apue神书时候看到的,方法比较冷门,通过使用select(),来设置定时器;原理利用select()方法的第5个参数,第一个参数设置为0,三个文件描述符集都设置为null,第5个参数为时间结构体,代码如下:

#include <sys/time.h>
#include <sys/select.h>
#include <time.h>
#include <stdio.h>

/*seconds: the seconds; mseconds: the micro seconds*/
void settimer(int seconds, int mseconds)
{
    struct timeval temp;

    temp.tv_sec = seconds;
    temp.tv_usec = mseconds;

    select(0, null, null, null, &temp);
    printf("timer\n");

    return ;
}

int main()
{
    int i;

    for(i = 0 ; i < 100; i++)
        settimer(1, 0);

    return 0;
}

这种方法精度能够达到微妙级别,网上有很多基于select()的多线程定时器,说明select()稳定性还是非常好。

总结:如果对系统要求比较低,可以考虑使用简单的sleep(),毕竟一行代码就能解决;如果系统对精度要求比较高,则可以考虑rtc机制和select()机制。

以上就是小编为大家带来的linux下实现定时器timer的几种方法总结全部内容了,希望大家多多支持~