0
考慮下列程序,除了每分鐘打印一次外,什麼也不做。 當我將/ etc/localtime鏈接更改爲不同的時區時,我希望它根據新時區打印時間,但它始終使用啓動時生效的時區。運行過程不遵循系統時間
即使在運行時區時,我如何使程序使用正確的時間?
BTW,該系統的CentOS 5.8
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define MAX_STIME_LEN 32
int
main()
{
while(1){
struct timeval timev;
gettimeofday(&timev,0);
struct tm now_tm;
time_t now = timev.tv_sec;
char saved_time[MAX_STIME_LEN];
strftime(saved_time, sizeof(saved_time), "%b %e %T", localtime_r (&now, &now_tm));
printf("%s\n",saved_time);
sleep(15);
}
}
請注意,使用則localtime_r和strftime而不是使用插件停止通話的,是必要的。這只是一個例子。
在調用localtime_r()之前添加tzset(),並確保在程序啓動時未設置TZ,解決問題。 – dbbd