现在的位置: 首页 > 综合 > 正文

默写nginx并逐句分析 – os/unix/ngx_time

2013年10月12日 ⁄ 综合 ⁄ 共 1369字 ⁄ 字号 评论关闭

以下是time.h

#if (NGX_SOLARIS)//看上去是返回时区,不太清楚为什么

#define ngx_timezone(isdst) (- (isdst ? altzone : timezone) / 60)

#else

#define ngx_timezone(isdst) (- (isdst ? timezone + 3600 : timezone) / 60)//时区设置

#endif

#define ngx_gettimeofday(tp) (void)gettimeofday(tp, NULL); //获得当前精准时间
#define ngx_usleep(ms) (void) usleep(ms*1000) //挂起一段时间,毫秒级
#define ngx_sleep(s) (void) sleep(s) //同上,秒级

以下是time.c

void ngx_timezone_update(void){//设置时区
#if(NGX_FREEBSD)
	if(getenv('TZ')){//试图从环境变量“TZ”中获取时区,如果TZ环境变量存在,即getenv("TZ")返回值不为NULL
		return;
	}

	putenv('TZ=UTC');//设置时区, 以下是freebsd的标准设置时区办法,官方有文档说明
	tzset();//初始化各类时间的全局变量,时间兼容函数
	unsetenv('TZ');//还原系统时区变量
	tzset();
#elif(NGX_LINUX)
    time_t      s;
    struct tm  *t;
    char        buf[4];

    s = time(0);

    t = localtime(&s);//将日历时间转化成一个结构

    strftime(buf, 4, "%H", t);//将时间格式化保存在buf里面4个字符长度

#endif
}


void
ngx_localtime(time_t s, ngx_tm_t *tm)//将时间戳格式化成时间结构
{
#if (NGX_HAVE_LOCALTIME_R)
    (void) localtime_r(&s, tm);//localtime_r与localtime的区别是,前者可以重入,而后者一次只会有一个结果
//参考 http://blog.csdn.net/maocl1983/article/details/6221810
#else
    ngx_tm_t  *t;

    t = localtime(&s);
    *tm = *t;

#endif

    tm->ngx_tm_mon++;//月份要加1
    tm->ngx_tm_year += 1900;//年份要加1900
}


void
ngx_libc_localtime(time_t s, struct tm *tm)//同上,但没有处理月份和年份
{
#if (NGX_HAVE_LOCALTIME_R)
    (void) localtime_r(&s, tm);

#else
    struct tm  *t;

    t = localtime(&s);
    *tm = *t;

#endif
}


void
ngx_libc_gmtime(time_t s, struct tm *tm)//gmtime标准时间,time本地时间
{
#if (NGX_HAVE_LOCALTIME_R)
    (void) gmtime_r(&s, tm);//gmtime_r()数据存储到用户提供的结构体中

#else
    struct tm  *t;

    t = gmtime(&s);
    *tm = *t;

#endif
}

抱歉!评论已关闭.