Linux kernel定时器timer_list
1.简单介绍一下定时器timer_list:
1.0 所在头文件:
linux/timer.h
1.1 结构体:
struct timer_list {
/*
* All fields that change during normal runtime grouped to the
* same cacheline
*/
struct list_head entry;
unsigned long expires;
struct tvec_base *base;
void (*function)(unsigned long);
unsigned long data;
int slack;
#ifdef CONFIG_TIMER_STATS
int start_pid;
void *start_site;
char start_comm[16];
#endif
#ifdef CONFIG_LOCKDEP
struct lockdep_map lockdep_map;
#endif
};
1.2 成员介绍:
list 实现的时候使用的,和定时器功能无关;
expires 是定时器定时的滴答数(当前的滴答数为jiffies);
void (*function)(unsigned long) 定时器超时处理函数;
data 传递到超时处理函数的参数,主要在多个定时器同时使用时,区别是哪个timer超时。
1.3 提供的API接口:
a. init_timer(struct timer_list*):定时器初始化函数;
b. add_timer(struct timer_list*):往系统添加定时器;
c. mod_timer(struct timer_list *, unsigned long jiffier_timerout):修改定时器的超时时间为jiffies_timerout;
d. timer_pending(struct timer_list ):定时器状态查询,如果在系统的定时器列表中则返回1,否则返回0;
e. del_timer(struct timer_list):删除定时器。
5. 使用方法:
a. 创建定时器时需要先定义struct timer_list my_timer;
b. 在file_operation指定的open函数中初始化定时器init_timer(&my_timer);
c. 在超时处理函数结尾重新加载定时器时间mod_timer(&my_timer,HZ);
d. 如果自己编写的驱动中有中断,需要在中断入口处del_timer(&my_timer);并且在入口处重新重新加载定时器时间mod_timer(&my_timer,HZ)。
2.实例演示
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>//jiffies在此头文件中定义
#include <linux/init.h>
#include <linux/timer.h>
struct timer_list timer;//定义一个定时器
void timer_function(unsigned long arg)
{
printk("Mytimer is ok\n");
printk("receive data from timer: %d\n",arg);
//mod_timer(&timer, jiffies + (5*HZ));//重新设置定时器,每隔5秒执行一次
}
static int __init chaos_init (void)
{
printk("chaos,world\n");
init_timer(&timer); //初始化定时器
timer.expires = jiffies+(5*HZ);//设定超时时间,5秒
timer.data = 5; //传递给定时器超时函数的值
timer.function = timer_function;//设置定时器超时函数
add_timer(&timer); //添加定时器,定时器开始生效
return 0;
}
static void __exit chaos_exit (void)
{
del_timer(&timer);//卸载模块时,删除定时器
printk("chaos module exit\n");
}
module_init(chaos_init);
module_exit(chaos_exit);
MODULE_AUTHOR("chaos");
MODULE_LICENSE("GPL");
3.总结
3.0 定义一个结构体:
static struct timer_list test_timer;
3.1 初始化
init_timer(&test_timer);
test_timer.function = timer_func;
add_timer(&test_timer);
3.2 10ms后启动定时器
mod_timer(&test_timer, jiffies+HZ/100); //HZ为1S,则HZ/100为10ms