gmtime_r和gmtime_s之间的区别

difference between gmtime_r and gmtime_s

本文关键字:gmtime 区别 之间      更新时间:2023-10-16

这两个函数有什么区别?我正在使用 MinGW 4.8.0。

我知道gmtime_r线程安全(但如果从同一线程多次调用则不安全),但我不明白gmtime_s

区别在于gmtime_r(3)是标准的 SUSv2 函数。在Windows环境中,您能找到的最接近gmtime_r()的是gmtime_s(),其参数颠倒了:

  • gmtime_r(const time_t*, struct tm*)
  • gmtime_s(struct tm*, const time_t*)

基本上,它们都将时间值转换为tm结构。 然后gmtime_r返回指向此结构的指针(如果失败,则返回NULL),而gmtime_s如果成功则返回0,如果失败则返回errno_t

tm结构具有以下正文,从上面列出的两个文档中可以看出:

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
};

gmtime_rlocaltime_r是标准的POSIX函数。

它们的主要目的是线程安全(重入)。 基本的 gmtimelocaltime 函数不是线程安全的或可重入的,因为它们使用单个静态区域来存储结果,因此 gmtime_rlocaltime_r 会指向结果应存储的位置的指针。

gmtime_slocaltime_s由Microsoft引入,现在是C11的一部分,尽管非Microsoft支持有限。(有关进一步讨论,请参阅此处。

它们的主要目的是安全性。 它们是作为Microsoft的安全CRT(安全C运行时)的一部分添加的。 据我了解,线程安全不是Microsoft CRT 中gmtimelocaltime的问题,因为这些函数的静态输出区域已经按线程分配。 相反,添加了gmtime_slocaltime_s来执行安全 CRT 的参数验证。(换句话说,它们检查其参数是否为 NULL,在这种情况下,它们会调用错误处理。