1,相关头文件:
#include
#include
#include
2,相关函数介绍:
定义定时器结构体变量:
static struct timer_list test_timer;
初始化内核定时器:
init_timer(struct timer_list *timer)
init_timer(&test_timer);
对timer_list成员变量进一步初始化:
test_timer.function=&timer_func;
test_timer.expires=jiffies + 100*(1000/HZ);
激活定时器
void add_timer(struct timer_list *timer)
add_timer(&test_timer);
停止定时器
int del_timer(struct timer_list *timer)
del_timer(&test_timer);
修改定时器expires
int mod_timer(struct timer_list * timer,unsigned long expires)//修改定时器的到期时间
mod_timer(&test_timer, jiffies + 100*(1000/HZ));
3,驱动例子:
#include
#include
#include
#include
#include
#include
#include
static struct timer_list test_timer;
static void timer_func(unsigned long data)
{
mod_timer(&test_timer,jiffies+100*(1000/HZ));
printk("test timer_func ++\n");
}
static int init_test_timer(void)
{
memset((void*)&test_timer,0,sizeof(test_timer));
test_timer.function=&timer_func;
test_timer.expires=jiffies+100*(1000/HZ);
init_timer(&test_timer);
add_timer(&test_timer);
return 0;
}
2 完整驱动实例:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#inlcude
init_timer(&test_devp->test_timer);
//进一步初始化定时器
test_devp->test_timer.function = &test_timer_handle;test_devp->test_timer.expires = jiffies + HZ;
//激活定时器
add_timer(&test_devp->test_timer); /*添加(注册)定时器*/static struct miscdevice misc_test={
.minor = MISC_DYNAMIC_MINOR,
.name= DEVICE_NAME,
.fops=&test_fops,
};
}
/*模块卸载函数*/module_exit(test_exit);
3,测试实例:
#include
#include
#include
#include
#include
#include
int main(int argc char **argv)
{
int fd;
int counter = 0;
int old_counter = 0;if(counter!=old_counter)
{
printf("seconds after open /dev/timertest :%d\n",counter);}
close(fd);
return 0;
}
4,运行结果:
seconds after open /dev/timertest :1
seconds after open /dev/timertest :2
seconds after open /dev/timertest :3
seconds after open /dev/timertest :4
seconds after open /dev/timertest :5