linux系统对时间函数的操作需要注意的问题

来源:互联网 发布:nosql数据库入门 pdf 编辑:程序博客网 时间:2024/06/07 07:28
简单点说,就是,在使用gmtime() 和 localtime()操作的时候,不能多次调用这些对struct tm结构体操作的函数,他们不是线程安全的。这些函数返回的指针实际上是指向同一个变量,多次操作会改变对应的struct tm的结构体中的数据。详见man gmtime


程序举例

#include <stdio.h>#include <time.h>int main(int argc, char ** argv){printf("process begin at \t[%p]\n", (void*)&main);time_t currentTime;time(&currentTime);printf("current time is \t[%d]\n", currentTime);struct tm *p_stm = gmtime(&currentTime);printf("address of struct tm *p_stm is \t[%p]. pointer to object is \t[%p]\n", &p_stm, p_stm);printf("struct tm *p_stm is \t[%d-%.2d-%.2d %.2d:%.2d:%.2d] time_zone is [%s]\n", p_stm->tm_year+1900, p_stm->tm_mon+1, p_stm->tm_mday, p_stm->tm_hour,p_stm->tm_min, p_stm->tm_sec, p_stm->tm_zone);struct tm *p_stm2 = localtime(&currentTime);printf("address of struct tm *p_stm2 is \t[%p]. pointer to object is \t[%p]\n", &p_stm2, p_stm2);printf("struct tm *p_stm2 is \t[%d-%.2d-%.2d %.2d:%.2d:%.2d] time_zone is [%s]\n", p_stm2->tm_year+1900, p_stm2->tm_mon+1, p_stm2->tm_mday, p_stm2->tm_hour,p_stm2->tm_min, p_stm2->tm_sec, p_stm2->tm_zone);printf("(*p_stm) after calling localtime() is \t[%d-%.2d-%.2d %.2d:%.2d:%.2d] time_zone is [%s]\n", p_stm->tm_year+1900, p_stm->tm_mon+1, p_stm->tm_mday, p_stm->tm_hour,p_stm->tm_min, p_stm->tm_sec, p_stm->tm_zone);return 0;}



程序的输出:
process begin at        [0x400594]
current time is         [1498122880]
address of struct tm *p_stm is  [0x7fffb9ebfbb0]. pointer to object is  [0x390f193420]
struct tm *p_stm is     [2017-06-22 09:14:40] time_zone is [GMT]
address of struct tm *p_stm2 is         [0x7fffb9ebfba8]. pointer to object is  [0x390f193420]
struct tm *p_stm2 is    [2017-06-22 17:14:40] time_zone is [CST]
(*p_stm) after calling localtime() is   [2017-06-22 17:14:40] time_zone is [CST]


说明:
根据日志,可以看到,上述程序中的gmtime()和localtime()所返回的结构体的地址是同一个,也就是说,定义的两个指针实际上是指向的同一个对象。当使用localtime()修改了struct tm的结构体指针的时候,gmtime()返回的指针所指向的对象也发生改变。


原创粉丝点击