wendykr
wendykr

Reputation: 255

How can i print current time in kernel?

i'm a beginner of linux. (sorry about my poor english) I should print current time and do something through system call in linux. I did other things but failed to print current time.. I wrote like

#include<linux/kernel.h>
#include<linux/time.h>
...
asmlinkage long sys_printtime(void) {
     ...
     struct timeval time;
     struct tm tm1;
     ...

     do_gettimeofday(&time);
     local_time=(u32)(time.tv_sec -(sys_tz.tz_minuteswest * 60));
     time_to_tm(local_time,(3600*9),&tm1);
     printk(KERN_DEBUG "time @(%04d-%02d-%02d %02d:%02d:%02d)\n", tm1.tm_year+1900,tm1.tm_mon+1,tm1.tm_mday,tm1.tm_hour,tm1.tm_min,tm1.tm_sec);
    ...
    return 0;
}

but it doesn't work.

The error said i can not use do_gettimeofday, and i finally knew that i can not use do_gettimeofday anymore because kernel5 doesn't support. I searched on google and stackoverflow, but i don't know how to print current time in kernel5.. anybody can help me?

Upvotes: 3

Views: 14700

Answers (2)

Hirbod Behnam
Hirbod Behnam

Reputation: 577

There is also a one liner to get the rtc time like this:

#include <linux/ktime.h>
#include <linux/rtc.h>

struct rtc_time t = rtc_ktime_to_tm(ktime_get_real());
printk(KERN_INFO "%ptRs", &t);

Document of ktime_get_real can be found here. I didn't find any documentation for rtc_ktime_to_tm even in the code but it gets the time as Unix epoch in nano seconds as input and outputs struct rtc_time. How to print struct rtc_time can be found here.

Upvotes: 1

bornfree
bornfree

Reputation: 2528

Yes, do_gettimeofday has been removed because of y2038 problem. Instead the kernel provides time interfaces which you can use as per your need. Check the documentation https://www.kernel.org/doc/html/latest/core-api/timekeeping.html.

For example, you have ktime_get_ts64(struct timespec64 *ts) which will provide you time in seconds and nanoseconds.

struct timespec64 {
    time64_t    tv_sec;         /* seconds */
    long        tv_nsec;        /* nanoseconds */
};

If you only want in nanoseconds, you can use u64 ktime_get_ns(void). Please check the documentation above for what suits your purpose. Also you can check timekeeping.h and ktime.h for further information.

If you want to find an example just search the function name in the kernel source either using grep -rni <func name> or use cscope. You can also search it online here

Upvotes: 4

Related Questions