nginx事件模块分析(一)

nginx ngx_events_module模块分析


    ngx_events_module模块是核心模块之一,它是其它所有事件模块的代理模块。nginx在启动时只与events模块打交道,而由events模块来加载其它事件模块;这样做的一个好处就是在添加新的事件模块处理新增配置项时原有事件模块代码不需做任何改动。events模块功能非常简单,它只负责处理events配置项(由ngx_events_block函数处理)。ngx_events_block函数做三件事情:一、为其它事件模块创建存储配置项结构的指针数组,并调用其它事件模块的create_conf函数。二、调用ngx_conf_parse函数解析events配置块内的配置项。三、调用其它事件模块的init_conf函数。


ngx_events_block函数分析

static char *
ngx_events_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    char                 *rv;
    void               ***ctx;
    ngx_uint_t            i;
    ngx_conf_t            pcf;
    ngx_event_module_t   *m;

    if (*(void **) conf) {
        return "is duplicate";
    }

    /* count the number of the event modules and set up their indices */
	
    /***找出所有事件模块,对其ctx_index进行编号***/
    ngx_event_max_module = 0;
    for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->type != NGX_EVENT_MODULE) {
            continue;
        }

        ngx_modules[i]->ctx_index = ngx_event_max_module++;
    }

    ctx = ngx_pcalloc(cf->pool, sizeof(void *));
    if (ctx == NULL) {
        return NGX_CONF_ERROR;
    }

    /***分配存储其它事件模块配置项结构的指针数组***/
    *ctx = ngx_pcalloc(cf->pool, ngx_event_max_module * sizeof(void *));
    if (*ctx == NULL) {
        return NGX_CONF_ERROR;
    }

    *(void **) conf = ctx;

    /***调用其它事件模块的create_conf函数***/
    for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->type != NGX_EVENT_MODULE) {
            continue;
        }

        m = ngx_modules[i]->ctx;

        if (m->create_conf) {
            (*ctx)[ngx_modules[i]->ctx_index] = m->create_conf(cf->cycle);
            if ((*ctx)[ngx_modules[i]->ctx_index] == NULL) {
                return NGX_CONF_ERROR;
            }
        }
    }

    /***保存解析events配置项时的配置结构***/
    pcf = *cf;
    /***在解析events{}内的配置项时,需要用到上面创建的ctx指针数组***/
    cf->ctx = ctx;
    cf->module_type = NGX_EVENT_MODULE;
    cf->cmd_type = NGX_EVENT_CONF;

    /***递归解析events {}内的配置项***/
    rv = ngx_conf_parse(cf, NULL);

    /***恢复配置结构***/
    *cf = pcf;

    if (rv != NGX_CONF_OK)
        return rv;

    /***调用其它事件模块的init_conf函数***/
    for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->type != NGX_EVENT_MODULE) {
            continue;
        }

        m = ngx_modules[i]->ctx;

        if (m->init_conf) {
            rv = m->init_conf(cf->cycle, (*ctx)[ngx_modules[i]->ctx_index]);
            if (rv != NGX_CONF_OK) {
                return rv;
            }
        }
    }

    return NGX_CONF_OK;
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值