Linux 内核定时器

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_init(timer_init);
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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值