Linux内核 timespec_equal()

函数:timespec_equal()

函数timespec_equal()判断两个timespec类型的变量表示的时间是否相同。

文件包含:

#include<linux/time.h>

函数定义:

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

函数定义格式:

static inline int timespec_equal(const struct timespec *a, const struct timespec *b)
{
    return (a->tv_sec == b->tv_sec) && (a->tv_nsec == b->tv_nsec);
}

输入参数说明:

  • 此函数的参数是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。

返回参数说明:

  • 函数timespec_equal()返回值是int型,可能的取值是0、1,如果返回0时说明此两个timespec类型的变量表示的时间不相同,如果返回1说明此两个timespec类型的变量表示的时间相同。

实例解析:

编写测试文件:timespec_equal.c

头文件引用:

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

模块加载函数定义:

int __init timespec_equal_init(void)
{
    int result_equ; //用于保存函数timespec_equ()的返回结果

    /*定义两个timespec类型的变量,作为函数的参数*/
    struct timespec lhs=
    {
        .tv_sec=10,
        .tv_nsec=110
    };
    struct timespec rhs=
    {
        .tv_sec=9,
        .tv_nsec=100
    };
    printk("timespec_equal begin.\n");
    result_equ=timespec_equal(&lhs, &rhs);                      //判断时间是否相同
    printk("the timespec equal result is: %d\n", result_equ); //显示时间是否相等的结果

    printk("timespec_equal over.\n");
    return 0;
}

模块退出函数定义:

void __exit timespec_equal_exit(void)
{
    printk("Goodbye timespec_equal\n");
}

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

module_init(timespec_equal_init);
module_exit(timespec_equal_exit);

实例运行结果及分析:

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

Linux内核 timespec_equal()

改变函数的输入参数,可能会出现如图B所示的结果。

Linux内核 timespec_equal()

结果分析:

A说明当参加比较的时间不相同时函数的返回值是0,图B说明当参加比较的时间相同时函数的返回值是1。

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!