在Linux内核中使用hrtimer

在Linux内核中使用hrtimer,linux,timer,Linux,Timer,在网上和Stackoverflow上搜索了大量时间后,我意识到在Linux内核中使用HRTimer的具体示例并不多。我发现的任何例子都是含糊不清的,没有解释他们程序的功能,也没有解释HRTimer如何工作得足够好,我无法理解 我知道在/include/linux/hrtimer.h上有文档,但文档不清楚,似乎认为我已经熟悉了它们 有人能给出一个使用这个定时器的基本例子吗 简单示例,每100ms回调一次: #include <linux/kernel.h> #include <l

在网上和Stackoverflow上搜索了大量时间后,我意识到在Linux内核中使用HRTimer的具体示例并不多。我发现的任何例子都是含糊不清的,没有解释他们程序的功能,也没有解释HRTimer如何工作得足够好,我无法理解

我知道在
/include/linux/hrtimer.h
上有文档,但文档不清楚,似乎认为我已经熟悉了它们


有人能给出一个使用这个定时器的基本例子吗

简单示例,每100ms回调一次:

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/hrtimer.h>
#include <linux/ktime.h>

static struct hrtimer test_hrtimer;
static u64 sampling_period_ms = 100; // 100ms
static u32 loop = 0;

static enum hrtimer_restart test_hrtimer_handler(struct hrtimer *timer)
{
    pr_info("test_hrtimer_handler: %u\n", ++loop);
    hrtimer_forward_now(&test_hrtimer, ms_to_ktime(sampling_period_ms));
    return HRTIMER_RESTART;
}

static int __init test_hrtimer_init(void)
{
    hrtimer_init(&test_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
    test_hrtimer.function = &test_hrtimer_handler;
    hrtimer_start(&test_hrtimer, ms_to_ktime(sampling_period_ms), HRTIMER_MODE_REL);
    pr_info("init test_hrtimer.\n");

    return 0;
}

static void __exit test_hrtimer_exit(void)
{
    hrtimer_cancel(&test_hrtimer );
    pr_info("exit test_hrtimer.\n");
    return;
}

module_init(test_hrtimer_init);
module_exit(test_hrtimer_exit);

MODULE_LICENSE("GPL");
#包括
#包括
#包括
#包括
静态结构计时器测试\u hr计时器;
静态u64采样周期=100;//100毫秒
静态u32环路=0;
静态枚举计时器\u重新启动测试\u计时器\u处理程序(结构计时器*计时器)
{
pr_info(“测试计时器处理程序:%u\n”,++循环);
hrtimer_forward_now(&test_hrtimer,ms_to_ktime(采样周期ms));
返回HRU重新启动;
}
静态整数初始化测试计时器初始化(无效)
{
hrtimer_init(&test_hrtimer,时钟单调,hrtimer_MODE_REL);
test\hrtimer.function=&test\hrtimer\u处理程序;
hrtimer\u启动(和测试\u hrtimer、毫秒到毫秒(采样周期\u毫秒)、hrtimer\u模式\u REL);
pr_info(“初始化测试计时器。\n”);
返回0;
}
静态无效\退出测试\计时器\退出(无效)
{
hrtimer\u cancel(&test\u hrtimer);
pr_info(“退出测试计时器。\n”);
返回;
}
模块初始化(测试定时器初始化);
模块退出(测试计时器退出);
模块许可证(“GPL”);