linux localtime

来源:互联网 发布:3dmax下载mac 破解版 编辑:程序博客网 时间:2024/05/21 01:43


#include <stdio.h>#include <time.h>#include <sys/time.h>int main(void){    time_t tNow = time(NULL);    printf("tNow %ld\n",tNow);    struct tm* ptnow = localtime(&tNow);    char szTmp[64] = {0};    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptnow);    printf("szTmp %s\n",szTmp);    time_t tEnd = tNow + 360;    struct tm* ptend = localtime(&tEnd);    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptend);    printf("szTmp %s\n",szTmp);    struct timeval tv1;    gettimeofday(&tv1,NULL);    sleep(3);    struct timeval tv2;    gettimeofday(&tv2,NULL);    printf("tv1 %ld\n",tv1.tv_sec);    printf("tv2 %ld\n",tv2.tv_sec);    return 0;}


修改下localtime的位置

#include <stdio.h>#include <time.h>#include <sys/time.h>int main(void){    time_t tNow = time(NULL);    printf("tNow %ld\n",tNow);    struct tm* ptnow = localtime(&tNow);    time_t tEnd = tNow + 360;    struct tm* ptend = localtime(&tEnd);    char szTmp[64] = {0};    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptnow);    printf("szTmp %s\n",szTmp);    strftime(szTmp, sizeof(szTmp), "%H:%M:%S",ptend);    printf("szTmp %s\n",szTmp);//same as before    struct timeval tv1;    gettimeofday(&tv1,NULL);    sleep(3);    struct timeval tv2;    gettimeofday(&tv2,NULL);    printf("tv1 %ld\n",tv1.tv_sec);    printf("tv2 %ld\n",tv2.tv_sec);    return 0;}


       The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone.  The return value points to a statically allocated struct which might be overwritten by  sub‐sequent calls to any of the date and time functions.  The localtime_r() function does the same, but stores the data in a user-supplied struct.


查阅localtime的文档,发现这段话:

This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

也就是说每次只能同时使用localtime()函数一次,要不就会被重写!

The localtime() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

因此localtime()不是可重入的。同时libc里提供了一个可重入版的函数localtime_r();

Unlike localtime(), the reentrant version is not required to set tzname。


这点跟inet_ntoa是一样的

点击查看

0 0
原创粉丝点击