1、<linux/timer.h>
定时器数据结构
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
};
初始化定时器
void init_timer_key(struct timer_list *timer,
const char *name,
struct lock_class_key *key);
kernel/timer.c
/**
* init_timer_key - initialize a timer
* @timer: the timer to be initialized
* @name: name of the timer
* @key: lockdep class key of the fake lock used for tracking timer
* sync lock dependencies
*
* init_timer_key() must be done to a timer prior calling *any* of the
* other timer functions.
*/
void init_timer_key(struct timer_list *timer,
const char *name,
struct lock_class_key *key)
{
debug_init(timer);
__init_timer(timer, name, key);
}
EXPORT_SYMBOL(init_timer_key);
#define init_timer(timer)\
init_timer_key((timer), NULL, NULL)
注册定时器到内核
void add_timer(struct timer_list *timer);
删除定时器
int del_timer(struct timer_list * timer);
2、Linux内核定时器简单实例
1)源代码文件
#include <linux/module.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <asm/uaccess.h> /*jiffies*/
static struct timer_list timer; //定义定时器
void timer_function(int para)
{
printk(KERN_INFO "Timer Expired and para is %d !!\n", para);
}
static __init timer_init(void)
{
init_timer(&timer);// 初始化定时器
timer.data = 5;
timer.expires = jiffies + (5 * HZ); //设置定时器超时时间
timer.function = timer_function;
add_timer(&timer); // 将定时器注册到内核
printk(KERN_INFO "timer_init\n");
return 0;
}
static __exit timer_exit(void)
{
del_timer(&timer); // 删除定时器
printk(KERN_INFO "timer_exit\n");
}
module_exit(timer_exit);
MODULE_LICENSE("GPL");
MODULE_VERSION("v1.0");
MODULE_AUTHOR("xz@vichip.com.cn");
MODULE_DESCRIPTION("Timer Module");
MODULE_ALIAS("timer module");
2)Makefile
ifeq ($(KERNELRELEASE),)
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KERNELDIR) M=$(PWD) clean
else
obj-m := timer.o
endif