您的位置:首页 > 运维架构 > Nginx

nginx之main函数的解读(九)

2014-10-20 10:56 3027 查看
接上次,我们应该进行的是ngx_os_init(log)函数了,而该函数定义在os文件夹中的unix文件夹当中的ngx_posix_init.c文件当中,该函数的定义是

ngx_int_t
ngx_os_init(ngx_log_t *log)
{
    ngx_uint_t  n;

#if (NGX_H***E_OS_SPECIFIC_INIT)
     //如果已经指定了操作系统版本号,那么ngx_os_specific_init的定义也就确定了
    if (ngx_os_specific_init(log) != NGX_OK) {
        return NGX_ERROR;
    }
#endif

    ngx_init_setproctitle(log);

    ngx_pagesize = getpagesize();
    ngx_cacheline_size = NGX_CPU_CACHE_LINE;

    for (n = ngx_pagesize; n >>= 1; ngx_pagesize_shift++) { /* void */ }

#if (NGX_H***E_SC_NPROCESSORS_ONLN)
    if (ngx_ncpu == 0) {
        ngx_ncpu = sysconf(_SC_NPROCESSORS_ONLN);
    }
#endif

    if (ngx_ncpu < 1) {
        ngx_ncpu = 1;
    }

    ngx_cpuinfo();

    if (getrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
        ngx_log_error(NGX_LOG_ALERT, log, errno,
                      "getrlimit(RLIMIT_NOFILE) failed)");
        return NGX_ERROR;
    }

    ngx_max_sockets = (ngx_int_t) rlmt.rlim_cur;

#if (NGX_H***E_INHERITED_NONBLOCK || NGX_H***E_ACCEPT4)
    ngx_inherited_nonblocking = 1;
#else
    ngx_inherited_nonblocking = 0;
#endif

    srandom(ngx_time());

    return NGX_OK;
}


操作系统的指定,现在先这样,先继续下一个话题吧

if (ngx_crc32_table_init() != NGX_OK) {
        return 1;
    }
ngx_crc32_table_init函数定义在core文件夹下的ngx_crc32.c文件当中

ngx_int_t
ngx_crc32_table_init(void)
{
    void  *p;
    //如果ngx_crc32_table_short的地址不是ngx_cacheline_size的整数倍,那么我们重新开辟内存空间存放该数据,只是为了数据在读取的时候速度比较快
    //(因为我们知道cpu在存取cpu位数整数倍的时候比较快)
    if (((uintptr_t) ngx_crc32_table_short
          & ~((uintptr_t) ngx_cacheline_size - 1))
        == (uintptr_t) ngx_crc32_table_short)
    {
        return NGX_OK;
    }
    //开辟内存空间,多了一个ngx_cacheline_size的数据是因为我们不一定从ngx_alloc返回的地址开始存放数据,保证数据从ngx_cacheline_size整数倍的地址开始
    p = ngx_alloc(16 * sizeof(uint32_t) + ngx_cacheline_size, ngx_cycle->log);
    if (p == NULL) {
        return NGX_ERROR;
    }
    //ngx_align_ptr宏定义在core文件当中的ngx_config.h文件中
    //#define ngx_align_ptr(p, a)      (u_char *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1)) 
    //p+  p和a求余的数值,保证返回p是a的整数倍
    //地址移位,保证p是ngx_cacheline_size
    //的整数倍,也就是说,如果输入p是63 ngx_cacheline_size是64,那么返回的就是p=64,如果输入p是65那么返回的就是128
    p = ngx_align_ptr(p, ngx_cacheline_size);
    //复制CRC冗余校验的数组
    ngx_memcpy(p, ngx_crc32_table16, 16 * sizeof(uint32_t));

    ngx_crc32_table_short = p;

    return NGX_OK;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: