首页 > 系统教程 > LINUX > 正文

定时器 Timer 在 Linux 下的多种应用方法及优缺点

WBOY
发布: 2024-07-19 08:49:12
转载
755人浏览过

定时器Timer应用场景十分广泛,在Linux下linux 应用定时器,有以下几种方式:

1红旗linux桌面版,使用sleep()和usleep()

其中sleep精度是一秒,usleep精度是1微妙,具体代码就不写了。使用这些技巧缺点比较显著,在Linux系统中,sleep类函数不能保证精度,尤其在系统负载比较大时,sleep通常还会有超时现象。

2,使用讯号量SIGALRM+alarm()

这些方法的精度能达到一秒,其中借助了*nix系统的讯号量机制,首先注册讯号量SIGALRM处理函数,调用alarm(),设置定时宽度,代码如下:

#include 
#include 
void timer(int sig)
{
if(SIGALRM == sig)
{
printf("timern");
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;
}
登录后复制

应用定时器设计电子钟_应用定时器2安卓版下载_linux 应用定时器

alarm方法尽管挺好,而且难以首先高于一秒的精度。

3,使用RTC机制

RTC机制借助系统硬件提供的RealTimeClock机制,通过读取RTC硬件/dev/rtc,通过ioctl()设置RTC频度,代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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("timern");
}
/* Disable periodic interrupts */
ioctl(fd, RTC_PIE_OFF, 0);
close(fd);
return 0;
}
登录后复制

这些方法比较便捷,借助了系统硬件提供的RTC,精度可调,并且特别高。

4,使用select()

这些方式在看APUE神书时侯听到的,技巧比较小众linux 应用定时器linux常用命令,通过使用select(),来设置定时器;原理借助select()方式的第5个参数,第一个参数设置为0,三个文件描述符集都设置为NULL,第5个参数为时间结构体,代码如下:

#include 
#include 
#include 
#include 
/*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("timern");
return ;
}
int main()
{
int i;
for(i = 0 ; i < 100; i++)
setTimer(1, 0);
return 0;
}
登录后复制

这些技巧精度才能达到微妙级别,网上有好多基于select()的多线程定时器,说明select()稳定性还是十分好。

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

以上就是定时器 Timer 在 Linux 下的多种应用方法及优缺点的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:ITcool网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号