Linux内核 timespec_add_ns()

函数:timespec_add_ns()

timespec_add_ns()函数实现timespec结构体变量与整数的相加,无符号整数表示的是纳秒数,结果保存在结构体变量中。

文件包含:

#include<linux/time.h>

函数定义:

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

函数定义格式:

static __always_inline void timespec_add_ns(struct timespec *a, u64 ns)
{
        a->tv_sec += __iter_div_u64_rem(a->tv_nsec + ns, NSEC_PER_SEC, &ns);
        a->tv_nsec = ns;
}

输入参数说明:

  • 该函数的第一个参数是一个struct timespec类型的结构体变量,定义见文件linux-3.19.3/include/uapi/linux/time.h,其定义如下:
struct timespec {
    __kernel_time_t         tv_sec;         /*秒数*/
    long                    tv_nsec;        /* 纳秒数*/
};
  • 该结构体是表示时间的一种方法,字段tv_sec表示的是秒数,字段tv_nsec表示不足一秒部分的时间,用纳秒表示,在此其取值范围是0~999999999。

  • 该函数的第二个参数是一个64位的无符号整数,表示的是纳秒,与第一个参数的字段tv_nsec相加,结果大于999999999则向结构体的字段tv_sec进位。

返回参数说明:

  • 此函数没有返回值,相加的结果保存在结构体变量中,__always_inline代表该函数始终是内联的且不能调用其他的内核函数。

实例解析:

编写测试文件:timespec_add_ns.c

头文件引用:

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

模块加载函数定义:

int timespec_add_ns_init(void)
{
    printk("timespec_add_ns begin.\n");
    // 声明变量,函数的第一个参数
    struct timespec ts={
        .tv_sec=1,
        .tv_nsec=1
    };
    u64 ns=1000000001;                     //64位无符号整数,函数的第二个参数
    printk("the value of the timespec before timespec_add_ns\n");
    printk("the tv_sec of the timespec is:%ld\n", ts.tv_sec); //显示参与加之前的数据
    printk("the tv_nsec of the timespec is:%ld\n", ts.tv_nsec);
    printk("the add ns is:%lld\n", ns);
    timespec_add_ns(&ts, ns);              //调用函数实现结构体变量与加整数的相加
    printk("the value of timespec after the timespec_add_ns :\n");
                                           //显示参与加之后的数据
    printk("the new tv_sec of the timespec is:%ld\n", ts.tv_sec);
    printk("the new tv_nsec of the timespec is:%ld\n", ts.tv_nsec);
    printk("timespec_add_ns over.\n");
    return 0;
}

模块退出函数定义:

void timespec_add_ns_exit(void)
{
    printk("Goodbye timespec_add_ns\n");
}

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

module_init(timespec_add_ns_init);
module_exit(timespec_add_ns_exit);

实例运行结果及分析:

执行命令insmod timespec_add_ns.ko插入模块,然后输入命令dmesg -c查看系统输出信息,出现如图所示结果。

Linux内核 timespec_add_ns()

结果分析:

  • 由图可以看出函数timespec_add_ns()的作用如前面所述,能够实现timespec结构体变量与无符号整数的相加,结果保存在timespec结构体变量中。

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!