加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何检查系统是否支持“Monotonic Clock”?

发布时间:2020-12-15 21:20:15 所属栏目:安全 来源:网络整理
导读:我需要在代码中处理超时场景,并且如果系统支持Monotonic Clock,则需要使用clock_gettime(CLOCK_MONOTONIC). #ifdef CLOCK_MONOTONIC clock_gettime(CLOCK_MONOTONIC, spec);#else clock_gettime(CLOCK_REALTIME, spec);#endif 我不确定这是否足够.也就是说,
我需要在代码中处理超时场景,并且如果系统支持Monotonic Clock,则需要使用clock_gettime(CLOCK_MONOTONIC).

#ifdef CLOCK_MONOTONIC
    clock_gettime(CLOCK_MONOTONIC,& spec);
#else
    clock_gettime(CLOCK_REALTIME,& spec);
#endif

我不确定这是否足够.也就是说,系统是否有可能定义CLOCK_MONOTONIC并不真正支持单调时钟?或者检查是否支持单调时钟的可靠方法是什么?

解决方法

根据POSIX的字母,即使定义了常量CLOCK_MONOTONIC,您实际上也可能需要运行时测试.处理此问题的官方方法是使用_POSIX_MONOTONIC_CLOCK“功能测试宏”,但这些宏的语义非常复杂:引用 http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/unistd.h.html,

If a symbolic constant is not defined or is defined with the value -1,the option is not supported for compilation. If it is defined with a value greater than zero,the option shall always be supported when the application is executed. If it is defined with the value zero,the option shall be supported for compilation and might or might not be supported at runtime.

将这种三向区分转换为代码会给你这样的东西:

#if !defined _POSIX_MONOTONIC_CLOCK || _POSIX_MONOTONIC_CLOCK < 0
    clock_gettime(CLOCK_REALTIME,&spec);
#elif _POSIX_MONOTONIC_CLOCK > 0
    clock_gettime(CLOCK_MONOTONIC,&spec);
#else
    if (clock_gettime(CLOCK_MONOTONIC,&spec))
        clock_gettime(CLOCK_REALTIME,&spec));
#endif

但是如果你在定义CLOCK_MONOTONIC本身时总是进行运行时测试,它会更简单,更易读:

#ifdef CLOCK_MONOTONIC
    if (clock_gettime(CLOCK_MONOTONIC,&spec))
#endif
        clock_gettime(CLOCK_REALTIME,&spec);

这会使支持CLOCK_MONOTONIC的当前操作系统的代码大小增加一些微不足道的数量,但在我看来,可读性的好处是值得的.

无条件使用CLOCK_MONOTONIC也有很强的理由;你有可能找到一个根本不支持clock_gettime的操作系统(例如MacOS X仍然没有它支持它),而不是一个具有clock_gettime但不支持CLOCK_MONOTONIC的操作系统.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读