gpt4 book ai didi

linux - 在 Linux 内核中使用 hrtimers

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:06 27 4
gpt4 key购买 nike

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

我知道在 /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");

关于linux - 在 Linux 内核中使用 hrtimers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54777424/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com