一、linux 内核定时器
1、定时主要用来出来一些耗时操作和消除按键抖动
2、Linux在include/linux/timer.h头文件中定义了数据结构timer_list来描述一个内核定时器
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); //函数指针function:指向一个可执行函数。当定时器到期时,内核就执行function所指定的函数。而data域则
被内核用作function函数的调用参数。
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
};
二、linux 内核定时器驱动例子
1、驱动代码 timer.c
#include <linux/init.h>#include <linux/module.h>
#include <linux/fs.h>
#include <linux/timer.h>
#include <linux/time.h>
#include <linux/jiffies.h>
#define TIME_OUT_EXIT 5
struct timer_list my_timer;
static int timeout=0;
void time_function(unsigned long data)
{
char *Tdata = (char *)data;
printk("time bootm function =%s\n",Tdata);
if(++timeout<5)
{
mod_timer(&my_timer,jiffies+10);
}
}
DEFINE_TIMER(my_timer,time_function,0,0);
static int __init timer_init(void)
{ //初始化定时器,并传递参数"test timer" 给 time_function回调函数
setup_timer(&my_timer,time_function,"test timer");
mod_timer(&my_timer,jiffies+10);
printk("timer init ! ...... \n");
return 0;
}
static void __exit timer_exit(void)
{
del_timer(&my_timer);
printk("timer exit!\n");
}
module_init(timer_init);
module_exit(timer_exit);
MODULE_LICENSE("Dual BSD/GPL");
2、Makefile 文件
CONFIG_CHARDEV ?=mobj-$(CONFIG_CHARDEV) +=timer.o
KERN_DIR =/home//rk3128_4.4_tb01_new_v3/kernel/
modules:
$(MAKE) -C $(KERN_DIR) M=$(PWD) modules
clean:
rm -rf chartest *.o *~core .depend. *.cmd *.ko *.mod.c .tmp_versions
3、安装驱动
insmod timer.ko 出现如下打印信息
<4>[ 2523.157238] time bootm function =test timer
<4>[ 2523.255647] time bootm function =test timer
<4>[ 2523.354027] time bootm function =test timer
<4>[ 2523.452438] time bootm function =test timer
<4>[ 2523.550837] time bootm function =test timer