Linux内核定时器
创始人
2025-05-30 03:37:21

1 内核时间管理简介
我们在编译 Linux 内核的时候可以通过图形化界面
设置系统节拍率,按照如下路径打开配置界面:

-> Kernel Features -> Timer frequency ( [=y])

在这里插入图片描述
高节拍率和低节拍率的优缺点:
①、高节拍率会提高系统时间精度,如果采用 100Hz 的节拍率,时间精度就是 10ms,采用
1000Hz 的话时间精度就是 1ms,精度提高了 10 倍。高精度时钟的好处有很多,对于那些对时
间要求严格的函数来说,能够以更高的精度运行,时间测量也更加准确。
②、高节拍率会导致中断的产生更加频繁,频繁的中断会加剧系统的负担,1000Hz 和 100Hz
的系统节拍率相比,系统要花费 10 倍的“精力”去处理中断。中断服务函数占用处理器的时间
增加,但是现在的处理器性能都很强大,所以采用 1000Hz 的系统节拍率并不会增加太大的负
载压力。
Linux 内核使用全局变量 jiffies 来记录系统从启动以来的系统节拍数,系统启动的时候会
将 jiffies 初始化为 0,jiffies 定义在文件 include/linux/jiffies.h 中,定义如下:

extern u64 __jiffy_data jiffies_64;
extern unsigned long volatile __jiffy_data jiffies;

Linux 内核提供了几个 jiffies 和 ms、us、ns 之间的转换函数如下图:
在这里插入图片描述

2 内核定时器简介

当超时时间到了以后设置的定时处理函数就会执行,和我们使用硬件定时器的套路一样,只是使用内核定时器不需要做一大堆的寄存器初始化工作。在使用内核定时器的时候要注意一点,内核定时器并不是周期性运行的,超时以后就会自动关闭,因此如果想要实现周期性定时,那么就需要在定时处理函数中重新开启定时器。

使用内核定时器首先要先定义一个 timer_list 变量,定义好定时器以后还需要通过一系列的 API 函数来初始化此定时器,这些函数如下:

init_timer 函数
init_timer 函数负责初始化 timer_list 类型变量,当我们定义了一个 timer_list 变量以后一定
要先用 init_timer 初始化一下。init_timer 函数原型如下:

void init_timer(struct timer_list *timer)

函数参数和返回值含义如下:
timer:要初始化定时器。
返回值:没有返回值。

add_timer 函数
add_timer 函数用于向 Linux 内核注册定时器,使用 add_timer 函数向内核注册定时器以后,
定时器就会开始运行,函数原型如下:

void add_timer(struct timer_list *timer)

函数参数和返回值含义如下:
timer:要注册的定时器。
返回值:没有返回值。

del_timer 函数
del_timer 函数用于删除一个定时器,不管定时器有没有被激活,都可以使用此函数删除。
在多处理器系统上,定时器可能会在其他的处理器上运行,因此在调用 del_timer 函数删除定时
器之前要先等待其他处理器的定时处理器函数退出。del_timer 函数原型如下:

int del_timer(struct timer_list * timer)

函数参数和返回值含义如下:
timer:要删除的定时器。
返回值:0,定时器还没被激活;1,定时器已经激活。

del_timer_sync 函数
del_timer_sync 函数是 del_timer 函数的同步版,会等待其他处理器使用完定时器再删除,
del_timer_sync 不能使用在中断上下文中。del_timer_sync 函数原型如下所示:

int del_timer_sync(struct timer_list *timer)

函数参数和返回值含义如下:
timer:要删除的定时器。
返回值:0,定时器还没被激活;1,定时器已经激活。

mod_timer 函数
mod_timer 函数用于修改定时值,如果定时器还没有激活的话,mod_timer 函数会激活定时
器!函数原型如下:

int mod_timer(struct timer_list *timer, unsigned long expires)

函数参数和返回值含义如下:
timer:要修改超时时间(定时值)的定时器。
expires:修改后的超时时间。
返回值:0,调用 mod_timer 函数前定时器未被激活;1,调用 mod_timer 函数前定时器已
被激活。

定时器使用框架代码如下:

struct timer_list timer; /* 定义定时器 *//* 定时器回调函数 */
void function(unsigned long arg)
{ /* * 定时器处理代码*//* 如果需要定时器周期性运行的话就使用 mod_timer* 函数重新设置超时值并且启动定时器。*/mod_timer(&dev->timertest, jiffies + msecs_to_jiffies(2000));
}/* 初始化函数 */
void init(void) 
{init_timer(&timer); /* 初始化定时器 */timer.function = function; /* 设置定时处理函数 */timer.expires=jffies + msecs_to_jiffies(2000);/* 超时时间 2 秒 */timer.data = (unsigned long)&dev; /* 将设备结构体作为参数 */add_timer(&timer); /* 启动定时器 */
}/* 退出函数 */
void exit(void)
{del_timer(&timer); /* 删除定时器 *//* 或者使用 */del_timer_sync(&timer);
}

Linux 内核短延时函数
在这里插入图片描述

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include #define TIMER_CNT		1		/* 设备号个数 	*/
#define TIMER_NAME		"timer"	/* 名字 		*/
#define CLOSE_CMD 		(_IO(0XEF, 0x1))	/* 关闭定时器 */
#define OPEN_CMD		(_IO(0XEF, 0x2))	/* 打开定时器 */
#define SETPERIOD_CMD	(_IO(0XEF, 0x3))	/* 设置定时器周期命令 */
#define LEDON 			1		/* 开灯 */
#define LEDOFF 			0		/* 关灯 *//* timer设备结构体 */struct timer_dev{dev_t devid;			/* 设备号 	 */struct cdev cdev;		/* cdev 	*/struct class *class;	/* 类 		*/struct device *device;	/* 设备 	 */int major;				/* 主设备号	  */int minor;				/* 次设备号   */struct device_node	*nd; /* 设备节点 */int led_gpio;			/* key所使用的GPIO编号		*/int timeperiod; 		/* 定时周期,单位为ms */struct timer_list timer;/* 定义一个定时器*/spinlock_t lock;		/* 定义自旋锁 */};struct timer_dev timerdev;	/* timer设备 *//** @description	: 初始化LED灯IO,open函数打开驱动的时候* 				  初始化LED灯所使用的GPIO引脚。* @param 		: 无* @return 		: 无*/static int led_init(void)
{int ret = 0;timerdev.nd = of_find_node_by_path("/gpioled");if (timerdev.nd== NULL) {return -EINVAL;}timerdev.led_gpio = of_get_named_gpio(timerdev.nd ,"led-gpio", 0);if (timerdev.led_gpio < 0) {printk("can't get led\r\n");return -EINVAL;}/* 初始化led所使用的IO */gpio_request(timerdev.led_gpio, "led");		/* 请求IO 	*/ret = gpio_direction_output(timerdev.led_gpio, 1);if(ret < 0) {printk("can't set gpio!\r\n");}return 0;}/** @description		: 打开设备* @param - inode 	: 传递给驱动的inode* @param - filp 	: 设备文件,file结构体有个叫做private_data的成员变量* 					  一般在open的时候将private_data指向设备结构体。* @return 			: 0 成功;其他 失败*/static int timer_open(struct inode *inode, struct file *filp)
{int ret = 0;filp->private_data = &timerdev;	/* 设置私有数据 */timerdev.timeperiod = 1000;		/* 默认周期为1s */ret = led_init();				/* 初始化LED IO */if (ret < 0) {return ret;}return 0;
}/** @description		: ioctl函数,* @param - filp 	: 要打开的设备文件(文件描述符)* @param - cmd 	: 应用程序发送过来的命令* @param - arg 	: 参数* @return 			: 0 成功;其他 失败*/static long timer_unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{struct timer_dev *dev =  (struct timer_dev *)filp->private_data;int timerperiod;unsigned long flags;switch (cmd) {case CLOSE_CMD:		/* 关闭定时器 */del_timer_sync(&dev->timer);break;case OPEN_CMD:		/* 打开定时器 */spin_lock_irqsave(&dev->lock, flags);timerperiod = dev->timeperiod;spin_unlock_irqrestore(&dev->lock, flags);mod_timer(&dev->timer, jiffies + msecs_to_jiffies(timerperiod));break;case SETPERIOD_CMD: /* 设置定时器周期 */spin_lock_irqsave(&dev->lock, flags)dev->timeperiod = arg;spin_unlock_irqrestore(&dev->lock, flags);mod_timer(&dev->timer, jiffies + msecs_to_jiffies(arg));break;default:break;}return 0;}/* 设备操作函数 */static struct file_operations timer_fops = {.owner = THIS_MODULE,.open = timer_open,.unlocked_ioctl = timer_unlocked_ioctl,
};/* 定时器回调函数 */void timer_function(unsigned long arg)
{struct timer_dev *dev = (struct timer_dev *)arg;static int sta = 1;int timerperiod;unsigned long flags;sta = !sta;		/* 每次都取反,实现LED灯反转 */gpio_set_value(dev->led_gpio, sta);/* 重启定时器 */spin_lock_irqsave(&dev->lock, flags);timerperiod = dev->timeperiod;spin_unlock_irqrestore(&dev->lock, flags);mod_timer(&dev->timer, jiffies + msecs_to_jiffies(dev->timeperiod)); }/** @description	: 驱动入口函数* @param 		: 无* @return 		: 无*/static int __init timer_init(void)
{/* 初始化自旋锁 */spin_lock_init(&timerdev.lock);/* 注册字符设备驱动 *//* 1、创建设备号 */if (timerdev.major) {		/*  定义了设备号 */timerdev.devid = MKDEV(timerdev.major, 0);register_chrdev_region(timerdev.devid, TIMER_CNT, TIMER_NAME);} else {						/* 没有定义设备号 */alloc_chrdev_region(&timerdev.devid, 0, TIMER_CNT, TIMER_NAME);	/* 申请设备号 */timerdev.major = MAJOR(timerdev.devid);	/* 获取分配号的主设备号 */timerdev.minor = MINOR(timerdev.devid);	/* 获取分配号的次设备号 */}/* 2、初始化cdev */timerdev.cdev.owner = THIS_MODULE;cdev_init(&timerdev.cdev, &timer_fops);/* 3、添加一个cdev */cdev_add(&timerdev.cdev, timerdev.devid, TIMER_CNT);/* 4、创建类 */timerdev.class = class_create(THIS_MODULE, TIMER_NAME);if (IS_ERR(timerdev.class)) {return PTR_ERR(timerdev.class);}/* 5、创建设备 */timerdev.device = device_create(timerdev.class, NULL, timerdev.devid, NULL, TIMER_NAME);if (IS_ERR(timerdev.device)) {return PTR_ERR(timerdev.device);}/* 6、初始化timer,设置定时器处理函数,还未设置周期,所有不会激活定时器 */init_timer(&timerdev.timer);timerdev.timer.function = timer_function;timerdev.timer.data = (unsigned long)&timerdev;return 0;
}/** @description	: 驱动出口函数* @param 		: 无* @return 		: 无*/static void __exit timer_exit(void)
{gpio_set_value(timerdev.led_gpio, 1);	/* 卸载驱动的时候关闭LED */del_timer_sync(&timerdev.timer);		/* 删除timer */#if 0del_timer(&timerdev.tiemr);#endif/* 注销字符设备驱动 */gpio_free(timerdev.led_gpio);		cdev_del(&timerdev.cdev);/*  删除cdev */unregister_chrdev_region(timerdev.devid, TIMER_CNT); /* 注销设备号 */device_destroy(timerdev.class, timerdev.devid);class_destroy(timerdev.class);}module_init(timer_init);
module_exit(timer_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("hsd");

app

#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include "linux/ioctl.h"/* 命令值 */#define CLOSE_CMD 		(_IO(0XEF, 0x1))	/* 关闭定时器 */
#define OPEN_CMD		(_IO(0XEF, 0x2))	/* 打开定时器 */
#define SETPERIOD_CMD	(_IO(0XEF, 0x3))	/* 设置定时器周期命令 */
/** @description		: main主程序* @param - argc 	: argv数组元素个数* @param - argv 	: 具体参数* @return 			: 0 成功;其他 失败*/int main(int argc, char *argv[])
{int fd, ret;char *filename;unsigned int cmd;unsigned int arg;unsigned char str[100];if (argc != 2) {printf("Error Usage!\r\n");return -1;}filename = argv[1];fd = open(filename, O_RDWR);if (fd < 0) {printf("Can't open file %s\r\n", filename);return -1;}while (1) {printf("Input CMD:");ret = scanf("%d", &cmd);if (ret != 1) {				/* 参数输入错误 */gets(str);				/* 防止卡死 */}if(cmd == 1)				/* 关闭LED灯 */cmd = CLOSE_CMD;else if(cmd == 2)			/* 打开LED灯 */cmd = OPEN_CMD;else if(cmd == 3) {cmd = SETPERIOD_CMD;	/* 设置周期值 */printf("Input Timer Period:");ret = scanf("%d", &arg);if (ret != 1) {			/* 参数输入错误 */gets(str);			/* 防止卡死 */}}ioctl(fd, cmd, arg);		/* 控制定时器的打开和关闭 */	}close(fd);}

相关内容

热门资讯

牛首山与栖霞山门票全攻略:多少... 牛首山与栖霞山门票全攻略:多少钱?有套票吗?本地人告诉你怎样玩最值! 来南京玩,想把行程安排得明明白...
再破两百万 迈步从头越——盐城... 再破两百万 迈步从头越 盐城机场2025年旅客吞吐量 再破200万人次大关 2025年12月...
2026年新质文旅的12个热门... 随着文旅产业的蓬勃发展,2025年迎来新质文旅的崭新篇章。在这个充满机遇与挑战的时代,文旅行业正以前...
原创 非... 今天凌晨,非洲杯小组赛第2轮展开激烈角逐,世界排名第90的赞比亚队迎战排名第108的科摩罗队。首轮比...
原创 朋... 标题:朋友来串门,要求我煮个粥和做这个菜,不用五块钱,吃的非常开心。 在这个快节奏的时代,人们往往...