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

Die*_*ras 2 c linux kernel kernel-module linux-kernel

我有这个代码,我正在尝试使内核模块打印系统的正常运行时间,完全在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;
} 
Run Code Online (Sandbox Code Playgroud)

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

error: implicit declaration of function ‘sysinfo’ [-Werror=implicit-function-declaration]
     sysinfo(&info);
Run Code Online (Sandbox Code Playgroud)

有谁知道其他任何有效的方法?

谢谢

Nom*_*mal 5

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

目前,相关的代码是

#include <linux/ktime.h>

    struct timespec  uptime;
    get_monotonic_boottime(&uptime);
Run Code Online (Sandbox Code Playgroud)

其中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());
Run Code Online (Sandbox Code Playgroud)

以毫秒为单位获得正常运行时间.如果您只需要整秒,请使用

#include <linux/ktime.h>

    s64  uptime;
    uptime = ktime_divns(ktime_get_coarse_boottime(), NSEC_PER_SEC);
Run Code Online (Sandbox Code Playgroud)

("粗略"表示只读取完整的秒部分.)