如何在Linux下实现定时器

来源:百度文库 编辑:神马文学网 时间:2024/04/19 18:38:00
百度首页 |百度空间 |登录
zkheartboy's Linux life
--生活空间--学习历程--
主页博客相册|个人档案 |好友
查看文章
如何在Linux下实现定时器
2007-11-28 00:10
在Linux实现一个定时器,不像Win32下那样直观。在Win32调用SetTimer就行了,在Linux下则没有相应函数可以直接调用。定时器作为一个常用的功能,在Linux当然也有相应实现。下面我们看看几种常用的方法。
要实现定时器功能,最土的办法实现莫过于用sleep/usleep来实现了。当然,它会阻塞当前线程,除了处理定时功能外,什么活也干不了。当然要解决这个问题不难,创建一个单独的线程来负责定时器,其它线程负责正常的任务就行了。
要实现定时器功能,最简单的办法就是ALARM信号。这种方法简单,也相应的缺陷:用信号实现效率较低; 最小精度为1秒,无法实现高精度的定义器。简单示例:
#include
#include
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
#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, 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
#include
#include
#include
#include
int count = 0;
void set_timer()
{
struct itimerval itv, oldtv;
itv.it_interval.tv_sec = 1;
itv.it_interval.tv_usec = 0;
itv.it_value.tv_sec = 5;
itv.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &itv, &oldtv);
}
void sigalrm_handler(int sig)
{
count++;
printf("timer signal.. %d\n", count);
}
int main()
{
signal(SIGALRM, sigalrm_handler);
set_timer();
while (count < 30)
{}
exit(0);
}
类别:Program |添加到搜藏 | 浏览(187) |评论 (0)
上一篇:c语言hash table的实现    下一篇:curl使用教程
相关文章:
Linux下的定时器:alarm()与setit...Linux下的定时器
linux定时器的使用Linux中的定时器使用方法
第八讲 Linux设备驱动编程之定时...linux应用层定时器与休眠
Linux下定时器使用系统时钟硬件与LINUX时间表示 之...
最近读者:
登录后,您就出现在这里。
hhukk8900wangshaohua663444542
网友评论:
发表评论:
姓 名:   注册 |登录 *姓名最长为50字节
网址或邮箱: (选填)
内 容:
验证码:
看不清?

"); //-->
©2008 Baidu