Heng30的博客
搜索 分类 关于 订阅

如何在Linux驱动中使用定时器?

2025-03-14

在Linux驱动中,定时器是很常用的工具,可以让延时执行一些函数。下面的例子实现了延时一秒钟执行一次定时器回调函数。

驱动代码

// simple.c

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/timer.h>

static struct timer_list my_timer;

static void _cb(struct timer_list *t) {
    pr_info("timer callback function called [%ld]\n", jiffies);

    mod_timer(&my_timer, jiffies + msecs_to_jiffies(1000));
}

static int __init simple_init(void) {
    pr_info("simple_init\n");

    timer_setup(&my_timer, _cb, 0);
    mod_timer(&my_timer, jiffies + msecs_to_jiffies(1000));

    return 0;
}

static void __exit simple_exit(void) {
    pr_info("simple_exit\n");
    del_timer(&my_timer);
}

module_init(simple_init);
module_exit(simple_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("heng30");
MODULE_VERSION("v0.0.1");
MODULE_DESCRIPTION("A simple kernel module");

编译脚本

#!/bin/sh

top-dir = $(shell pwd)
kernel-version = $(shell uname -r)
kernel-dir ?= /lib/modules/$(kernel-version)/build

obj-m += simple.o

all:
        make -C $(kernel-dir) modules M=$(top-dir)

clean:
        rm -f *.o *.ko *.mod *.mod.c *.order *.symvers *.dtbo
        make -C $(kernel-dir) clean m=$(top-dir)

测试

  • 编译程序:make

  • 安装驱动:insmod simple.ko

  • 查看输出:dmesg

[  335.782919] simple_init
[  336.836639] timer callback function called [4295004036]
[  337.861367] timer callback function called [4295005061]
[  349.190383] timer callback function called [4295016389]
[  359.489337] timer callback function called [4295026688]
....
[  360.521728] timer callback function called [4295027720]
[  361.542054] timer callback function called [4295028740]
[  362.573191] timer callback function called [4295029771]
[  363.586786] timer callback function called [4295030785]
[  363.948287] simple_exit
  • 移除驱动:rmmod simple.ko