目录

Ubuntu-下-nginx-1.24.0-源码分析-ngx_cycle_modules

目录

Ubuntu 下 nginx-1.24.0 源码分析 - ngx_cycle_modules

声明src/core/ngx_module.h

ngx_int_t ngx_cycle_modules(ngx_cycle_t *cycle);

实现src/core/ngx_module.c

ngx_int_t
ngx_cycle_modules(ngx_cycle_t *cycle)
{
    /*
     * create a list of modules to be used for this cycle,
     * copy static modules to it
     */

    cycle->modules = ngx_pcalloc(cycle->pool, (ngx_max_module + 1)
                                              * sizeof(ngx_module_t *));
    if (cycle->modules == NULL) {
        return NGX_ERROR;
    }

    ngx_memcpy(cycle->modules, ngx_modules,
               ngx_modules_n * sizeof(ngx_module_t *));

    cycle->modules_n = ngx_modules_n;

    return NGX_OK;
}

这个函数 ngx_cycle_modules 的作用是为当前Nginx服务器周期(cycle)初始化并设置模块列表。具体来说:

  1. 函数为当前周期分配内存,用于存储模块指针数组

  2. 将静态定义的模块列表( ngx_modules )复制到当前周期的模块列表中

  3. 设置当前周期的模块数量


ngx_cycle_modules 函数的签名如下:

ngx_int_t ngx_cycle_modules(ngx_cycle_t *cycle);

以下是对函数签名的详细解析:


1. 返回值类型 ngx_int_t 类型定义:ngx_int_t 是 Nginx 自定义的整数类型,用于统一跨平台的整数表示。 语义: NGX_OK (值为 0):表示函数执行成功。 NGX_ERROR (值为 -1):表示函数执行失败(如内存分配失败)。 作用:通过返回状态码,通知调用者函数执行结果。

2. 参数 ngx_cycle_t *cycle 参数类型:ngx_cycle_t 是 Nginx 的核心结构体,表示一个运行周期(如启动、重载配置时的实例)。


详解


注释部分
/*
 * create a list of modules to be used for this cycle,
 * copy static modules to it
 */

作用:说明函数的核心目标。

背景: Nginx 的模块在编译时静态注册到全局数组 ngx_modules。 每个运行周期(cycle)需要独立的模块列表,以支持配置重载时的多实例隔离。

设计思想: 隔离性:通过复制全局模块到 cycle,避免不同周期(如旧配置与新配置)的模块相互干扰。


分配模块数组内存

cycle->modules = ngx_pcalloc(cycle->pool, (ngx_max_module + 1) * sizeof(ngx_module_t *));

作用:在 cycle 的内存池中分配内存,存储模块指针数组。

关键参数: cycle->pool :Nginx 内存池,确保高效内存管理(避免频繁 malloc/free)。 ngx_max_module + 1 : ngx_max_module 是编译时定义的最大模块数, +1 用于预留终止标记(如 NULL)


检查内存分配

if (cycle->modules == NULL) {
    return NGX_ERROR;
}
  • 作用 :验证内存分配是否成功。

  • 逻辑 :若 ngx_pcalloc 返回 NULL ,直接返回错误码 NGX_ERROR


复制全局模块到周期模块列表

ngx_memcpy(cycle->modules, ngx_modules, ngx_modules_n * sizeof(ngx_module_t *));

作用:将全局模块数组 ngx_modules 拷贝到 cycle->modules

关键变量: ngx_modules :全局静态模块数组,编译时生成。

ngx_modules_n :全局模块数量,编译时确定。

仅复制实际存在的模块(ngx_modules_n 个),而非整个预分配空间。


记录模块数量

cycle->modules_n = ngx_modules_n;
  • 作用 :将全局模块数量 ngx_modules_n 赋值给 cycle->modules_n

  • 逻辑

    • cycle->modules_n 后续用于遍历模块(如初始化模块时)


返回成功状态

return NGX_OK;
  • 作用 :通知调用者函数执行成功。