在内核空间中设置时间

时间:2014-12-12 15:12:17

标签: time linux-kernel kernel

我道歉但我完全是新手......

我正在尝试为自定义硬件编写自己的驱动程序。 我需要在内核中读取系统时间:

struct timeval time;
struct tm broken, mytime;

...
do_gettimeofday(&time);
time_to_tm(time.tv_sec, 0, &broken);
printk(KERN_INFO "Timer synced at %d:%d:%d:%ld\n", broken.tm_hour, broken.tm_min,broken.tm_sec, time.tv_usec);
...

这可行。

然后我手动设置: - broken.tm_hour - broken.tm_min ... - broken.tm_sec - time.tv_usec

我现在如何用我的值更新系统时间? 谢谢。

2 个答案:

答案 0 :(得分:0)

在用户空间中有几个函数:gettimeofday和settimeofday。可能是do_settimeofday?

答案 1 :(得分:0)

有很多方法可以将填充数据输入'struct timespec',我只是保持简单:

$ sudo insmod .ko hh = 2 mm = 50 ss = 10 nn = 600

/*
=========================================================
Execute   :  sudo insmod <MODULENAME>.ko hh=2 mm=50 ss=10 nn=600
Output    :  dmesg
=========================================================
*/

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/time.h>

static int hh, mm, ss, nn;

MODULE_LICENSE("GPL");
module_param(hh, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(hr, "Hours");
module_param(mm, uint, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(mm, "Minutes");
module_param(ss, uint, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(ss, "Seconds");
module_param(nn, uint, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(nn, "Nano seconds");

int __init ourinitmodule(void)
{

    struct timeval time;
    struct tm broken;
    struct timespec tp;
    printk(KERN_ALERT "\nWelcome to Module .... \n");
    do_gettimeofday(&time);
    time_to_tm(time.tv_sec, 0, &broken);
    printk(KERN_INFO "Timer synced at %d:%d:%d:%ld\n", broken.tm_hour, broken.tm_min,broken.tm_sec, time.tv_usec);
    // Iam trying to set time to 2:50:10:800 (HH:MM:SS:NN)
    tp.tv_sec= 3600/*constant*/ * hh /*hours*/ + 60 * mm /*minutes*/ + ss  /*seconds*/;
    tp.tv_nsec=1000* nn /*nanosec*/;
    do_settimeofday(&tp);
    do_gettimeofday(&time);
    time_to_tm(time.tv_sec, 0, &broken);
    printk(KERN_INFO "Timer set to %d:%d:%d:%ld\n", broken.tm_hour, broken.tm_min,broken.tm_sec, time.tv_usec);
    return 0;
}

void __exit ourcleanupmodule(void)
{
    printk(KERN_ALERT "Thanks....Exiting Module. \n");
}

module_init(ourinitmodule);
module_exit(ourcleanupmodule);

希望你得到你需要的东西。 快乐编程:)