Issue
I've got this code where I'm trying to make a kernel module print the uptime of the system, exactly on the 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;
}
This is what I would do if this wasn't a kernel module, I found that there's a similar linux library for sysinfo which is linux/sysinfo, but even when I use that one, it only has a Struct sysinfo and not a function I can call sysinfo(), and when I try to do so I get
error: implicit declaration of function ‘sysinfo’ [-Werror=implicit-function-declaration]
sysinfo(&info);
Does anyone knows any other effective approach?
Thanks
Solution
Since the information you seek is provided by the kernel pseudofile /proc/uptime
, we can look at fs/proc/uptime.c:uptime_proc_show() in the kernel sources to see how the information is gathered.
Currently, the relevant code is
#include <linux/ktime.h>
struct timespec uptime;
get_monotonic_boottime(&uptime);
where uptime.tv_sec
is the number of seconds, and uptime.tv_nsec
nanoseconds (0 to 999,999,999 inclusive).
However, since the kernel is moving to 64-bit time, you'd better use
#include <linux/ktime.h>
s64 uptime_ms;
uptime_ms = ktime_to_ms(ktime_get_boottime());
to get the uptime in milliseconds. If you only need the full seconds, use
#include <linux/ktime.h>
s64 uptime;
uptime = ktime_divns(ktime_get_coarse_boottime(), NSEC_PER_SEC);
("coarse" meaning only the full seconds part are read.)
Answered By - Nominal Animal Answer Checked By - Terry (WPSolving Volunteer)