gpt4 book ai didi

c - 如果过期,hrtimer 不会返回负值

转载 作者:太空宇宙 更新时间:2023-11-04 03:47:58 24 4
gpt4 key购买 nike

timeval v = ktime_to_timeval(hrtimer_get_remaining(timer));

我没有在计时器到期时得到一个负值(我预计 ~ 负 100 毫秒),我得到的是加 800 毫秒,这太离谱了,我无法在预期结果和实际结果之间建立任何联系。
我的第一个教导是 hrtimer_get_remaining 或 ktime_to_timeval 做错了什么,所以我使用了 ktime_to_timespec 和 hrtimer_expires_remaining,但结果是一样的。

还有其他建议吗?

最佳答案

简短回答

可能您得到了正确的结果,但您的解释是错误的。您的代码仅检查 tv_nsec,而忽略 tv_sec,它可能包含 -1。如果您添加 -1 秒并且比 800ms 多一点,您将获得您的 ~-100ms 值。

更长的解释

即使 ns_to_timespec 没有像之前那样调用 set_normalized_timespec,它仍然以相同的方式规范化 timespec 值。这是此函数的当前版本:

struct timespec ns_to_timespec(const s64 nsec)
{
struct timespec ts;
s32 rem;

if (!nsec)
return (struct timespec) {0, 0};

ts.tv_sec = div_s64_rem(nsec, NSEC_PER_SEC, &rem);
if (unlikely(rem < 0)) { // <-- here is normalization
ts.tv_sec--;
rem += NSEC_PER_SEC;
}
ts.tv_nsec = rem;

return ts;
}

仅供引用,几年前这种规范化是这样完成的:

if (unlikely(nsec < 0))
set_normalized_timespec(&ts, ts.tv_sec, ts.tv_nsec);

我提到这个是因为 set_normalized_timespec 函数上面有一条评论说:

Note: The tv_nsec part is always in the range of
0 <= tv_nsec < NSEC_PER_SEC
For negative values only the tv_sec field is negative !

此行为由 POSIX 标准定义。例如 what it says关于发出 nanosleep() 函数(rqtpstruct timespec * 类型)后可能出现的错误:

[EINVAL]
The rqtp argument specified a nanosecond value less than zero or greater than or equal to 1000 millio

这是来自 nanosleep(2) 的类似定义Linux 手册页:

结构 timespec 用于以纳秒精度指定时间间隔。定义如下:

struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};

The value of the nanoseconds field must be in the range 0 to 999999999.

请注意,在这两种情况下,都没有关于负 tv_sec 无效的信息。

简单证明

这是一个简单的内核模块,可以证明我的观点:

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

int init_module(void)
{
struct timeval v = ktime_to_timeval((ktime_t){.tv64 = -200000000});
printk(KERN_INFO "v= %ld, %ld\n", v.tv_sec, v.tv_usec);

return -1;
}

插入后,这是内核日志的输出:

v= -1, 800000

关于c - 如果过期,hrtimer 不会返回负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22880575/

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