C语言 获取内核模块中的当前时间(以秒为单位)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13552536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:33:45  来源:igfitidea点击:

Get current time in seconds in kernel module

ctimelinux-kernelkernel-module

提问by HXCaine

What is the standard way to get the current time in seconds (since the epoch) in a kernel module?

在内核模块中以秒为单位(自纪元以来)获取当前时间的标准方法是什么?

I have seen techniques involving getting xtime which are very long-winded and involve while-loops and locks. There must be a better way.

我见过涉及获取 xtime 的技术,这些技术非常冗长,涉及 while 循环和锁。一定会有更好的办法。

[This is not a duplicate. I have looked through previous questions on SO. The answers to many of these either don't specify the function used, or incorrectly refer to time.h which is not allowed in the kernel]

[这不是重复的。我已经浏览了以前关于 SO 的问题。其中许多的答案要么没有指定使用的函数,要么错误地引用了内核中不允许的 time.h]

回答by cnicutar

You can use getnstimeofdayfor that.

你可以用getnstimeofday它。

/* getnstimeofday - Returns the time of day in a timespec */
void getnstimeofday(struct timespec *ts)

where struct timespecis:

在哪里struct timespec

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

And yes, you'll need #include <linux/time.h>.

是的,你需要#include <linux/time.h>.