在内核空间中设置时间 [英] set time in kernel space

查看:158
本文介绍了在内核空间中设置时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉,但是我完全是新手...

I apologize but I'm totally newbie...

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

I'm trying to write my own driver for custom hardware. I need to read system time in 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 -破.tm_min ... -broken.tm_sec -time.tv_usec

Then I manually set: - broken.tm_hour - broken.tm_min ... - broken.tm_sec - time.tv_usec

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

how can I now update system time with my values? Thanks.

推荐答案

有很多方法可以将数据填充到"struct timespec"中,我只是保持其简单性:

There are many ways of fillings data into 'struct timespec', I am just keeping it simple:

$ 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);

希望您得到了所需的东西. 编程愉快:)

Hope you got what you need. Happy programming :)

这篇关于在内核空间中设置时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆