Linux内核 ns_to_timespec()

函数:ns_to_timespec( )

文件包含:

#include<linux/time.h>

函数定义:

在内核源码中的位置:linux-3.19.3/kernel/time/time.c

函数定义格式:

struct timespec ns_to_timespec(const s64 nsec)

函数功能描述:

  • 函数ns_to_timespec( )将参数表示的时间转换成用结构体timespec变量表示的时间,参数的时间单位是纳秒。

输入参数说明:

  • 此函数的输入参数是一个64位有符号整数,表示的是时间,单位是纳秒。

返回参数说明:

函数的返回值是struct timespec类型的结构体变量,定义见文件linux-3.19.3/include/uapi/linux/time.h,其声明如下:

struct timespec
{
    __kernel_time_t       tv_sec;         /*秒数*/
    long                    tv_nsec;        /*纳秒数*/
};

此结构体用于内核记录时间,其中字段tv_sec的单位是秒(s),表示整秒数,字段tv_nsec的单位是纳秒(ns),表示不足一秒的部分,在此其取值范围是0~999999999

实例解析:

编写测试文件:ns_to_timespec.c

头文件引用:

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

模块加载函数定义:

int __init ns_to_timespec_init(void)
{

    struct timespec ts;           //声明变量,用于保存函数执行结果
    const s64 nsec=1001000000;    //-1001000000,定义64位有符号整数,作为函数的参数
    printk("ns_to_timespec begin.\n");
    ts=ns_to_timespec(nsec);      //调用函数,将参数表示的时间转换成用timespec表示的时间
    printk("the value of the struct timespec is:\n"); //显示转换结果
    printk("the tv_sec value is:%ld\n", ts.tv_sec);    //秒数
    printk("the tv_nsec value is:%ld\n", ts.tv_nsec); //纳秒数
    printk("ns_to_timespec over.\n");
    return 0;
}

模块退出函数定义:

void __exit ns_to_timespec_exit(void)
{
    printk("Goodbye ns_to_timespec\n");
}

模块加载、退出函数调用:

module_init(ns_to_timespec_init);
module_exit(ns_to_timespec_exit);

实例运行结果及分析:

执行命令insmod ns_to_timespec.ko插入模块,然后输入命令dmesg -c,出现如图A所示结果。

Linux内核 ns_to_timespec()

如果将参数改为-1001000000,重新编译插入运行,出现如图B所示结果。

Linux内核 ns_to_timespec()

结果分析:

从图A和图B可以看出,两次函数调用都能将64位有符号整数表示的时间转变成结构体timespec变量所表示的时间,不论传入的参数是正数还是负数,都能正确转换,当然一般时间为负数是没有意义的。

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!