在内核模块上获得正常运行时间?

Getting uptime on a kernel module?

我有这段代码,我试图让内核模块打印系统的 uptime,正好在 simple_init 上.

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <sys/sysinfo.h>

/* This function is called when the module is loaded. */

int simple_init(void)
{
    struct sysinfo info;
    sysinfo(&info);
    printk("This pc has been on for %ld seconds\n", info.uptime);;
    printk(KERN_INFO "Loading Module\n");
    return 0;
} 

如果这不是内核模块,我会这样做,我发现 sysinfo 有一个类似的 linux 库,它是 linux/sysinfo,但即使我使用那个,它也只有一个 Struct sysinfo 而不是一个我可以调用 sysinfo() 的函数,当我尝试这样做时,我得到

error: implicit declaration of function ‘sysinfo’ [-Werror=implicit-function-declaration]
     sysinfo(&info);

有谁知道其他有效的方法吗?

谢谢

由于您查找的信息是由内核伪文件 /proc/uptime 提供的,我们可以查看内核源代码中的 fs/proc/uptime.c:uptime_proc_show() 以了解信息是如何收集的。

目前相关代码为

#include <linux/ktime.h>

    struct timespec  uptime;
    get_monotonic_boottime(&uptime);

其中 uptime.tv_sec 是秒数,uptime.tv_nsec 纳秒(包括 0 到 999,999,999)。

但是,由于内核正在向 64 位时间移动,您最好使用

#include <linux/ktime.h>

    s64  uptime_ms;
    uptime_ms = ktime_to_ms(ktime_get_boottime());

获取以毫秒为单位的正常运行时间。如果您只需要完整的秒数,请使用

#include <linux/ktime.h>

    s64  uptime;
    uptime = ktime_divns(ktime_get_coarse_boottime(), NSEC_PER_SEC);

("coarse" 表示只读取完整的秒部分。)