GeorgeCostanza
GeorgeCostanza

Reputation: 395

Custom Linux kernel module to display year, date and time

I'm experimenting with creating a custom linux kernel module. I want to display:

year-month-day hour:minute:second.

So far I've gotten hour:minute:second to work, but I can't get Year to work. I'm using "tm_year" from the linux/time.h header, but when I cat my module the Year isn't displaying correctly. It's just a long string of random numbers. Any help would be appreciated. I only have access to linux headers as the kernel needs to run in kernel space. The code is ugly, but I'm just experimenting right now:

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/time.h>
MODULE_LICENSE("GPL");

static int hello_proc_show(struct seq_file *m, void *v) {

// seq_printf(m, "Hello proc!\n");

unsigned long get_time;
int sec, hr, min, tmp1,tmp2, tmp3;
struct timeval tv;
struct tm tv2;

do_gettimeofday(&tv);
get_time = tv.tv_sec;
sec = get_time % 60;
tmp1 = get_time / 60;
min = tmp1 % 60;
tmp2 = tmp1 / 60;
hr = (tmp2 % 24) - 4;
tmp3 = tv2.tm_year;

seq_printf(m, "time ::  %d:%d:%d\n",hr,min,sec);
seq_printf(m, "Year: %d\n", tmp3);




 return 0;
}

Upvotes: 2

Views: 4891

Answers (2)

Ashok Vairavan
Ashok Vairavan

Reputation: 1962

This is what I used in my kernel module to get system time

    struct timeval now;
    struct tm tm_val;

    do_gettimeofday(&now);
    time_to_tm(now.tv_sec, 0, &tm_val);
    printk(KERN_INFO "%d/%d %02d:%02d:%02d Days since 1 Jan: %d\n", tm_val.tm_mon + 1,
                    1900 + tm_val.tm_year, tm_val.tm_hour, tm_val.tm_min,
                    tm_val.tm_sec, tm_val.tm_yday);

Upvotes: 1

Peter L.
Peter L.

Reputation: 1041

This works. I just tried it. You can use time_to_tm() to convert between values. Note that if you want to be very precise, use the system timezone to know hours, minutes, and seconds locally.

Also, I printed to the system log instead of a proc entry.

    unsigned long get_time;
    int sec, hr, min, tmp1,tmp2, tmp3;
    struct timeval tv;
    struct tm tv2;

    do_gettimeofday(&tv);
    get_time = tv.tv_sec;
    sec = get_time % 60;
    tmp1 = get_time / 60;
    min = tmp1 % 60;
    tmp2 = tmp1 / 60;
    hr = (tmp2 % 24) - 4;
    time_to_tm(get_time, 0, &tv2);
    tmp3 = tv2.tm_year;

    printk(KERN_INFO "time ::  %d:%d:%d\n",hr,min,sec);
    /* Add years since 1900. */
    printk(KERN_INFO "Year: %d\n", tmp3 + 1900);

Upvotes: 4

Related Questions