36.循环定时器实现
使用mod_timer实现1秒触发一次超时函数
loop_timer.c编写
#include <linux/module.h>
#include <linux/init.h>
#include <linux/time.h>static void timer_function(struct timer_list *timer);DEFINE_TIMER(test_timer,timer_function);static void timer_function(struct timer_list *timer){printk("this is timer test\n");mod_timer(&test_timer,jiffies_64 + msecs_to_jiffies(1000));
}static int helloworld_init(void){printk("hello timer\n");test_timer.expires = jiffies_64 + msecs_to_jiffies(5000);add_timer(&test_timer);return 0;
}
static void helloworld_exit(void){del_timer(&test_timer);printk("bye timer\n");
}module_init(helloworld_init);
module_exit(helloworld_exit);MODULE_LICENSE("GPL");
MODULE_AUTHOR("quan");
MODULE_VERSION("v1.0");Makefile编写
# KBUILD_CFLAGS_MODULE += -DDEBUG=3
EXTRA_CFLAGS += -DDEBUG=3
obj-m += loop_timer.o
KDIR:=/lib/modules/6.2.0-37-generic/build
# KDIR:=/usr/src/linux-source-6.2.0/
PWD?=$(shell pwd)
all:make -C $(KDIR) M=$(PWD) modulesecho $(PWD)
clean:rm -rf *.ko *.o *.mod *.mod.o *.mod.c *.symvers *.order
编译及测试
make
insmod loop_timer.ko
dmesg[37713.985682] hello timer
[37719.047808] this is timer test
[37720.071839] this is timer test
[37721.095743] this is timer test
[37722.119787] this is timer test
[37723.148052] this is timer test
[37724.168110] this is timer test
[37725.192501] this is timer test
[37726.216073] this is timer test
[37727.240389] this is timer test
[37728.264222] this is timer test
[37729.288053] this is timer test
[37730.312477] this is timer test
[37731.336195] this is timer test
[37732.360657] this is timer test
[37733.384699] this is timer test
[37734.408342] this is timer test
[37735.432616] this is timer test
[37736.456731] this is timer test
[37737.480489] this is timer test
[37738.504470] this is timer test