定义在 src\core\nginx.c
ngx_module_t ngx_core_module = {
NGX_MODULE_V1,
&ngx_core_module_ctx, /* module context */
ngx_core_commands, /* module directives */
NGX_CORE_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
模块的基本属性
ngx_module_t ngx_core_module = {
NGX_MODULE_V1,
&ngx_core_module_ctx, /* 模块上下文 */
ngx_core_commands, /* 模块支持的配置指令 */
NGX_CORE_MODULE, /* 模块类型 */
NULL, /* init_master 回调 */
NULL, /* init_module 回调 */
NULL, /* init_process 回调 */
NULL, /* init_thread 回调 */
NULL, /* exit_thread 回调 */
NULL, /* exit_process 回调 */
NULL, /* exit_master 回调 */
NGX_MODULE_V1_PADDING
};
字段解析:
-
NGX_MODULE_V1
宏定义,用于初始化模块的版本和兼容性字段(如 ctx_index
, index
等)。确保模块在不同 Nginx 版本间的兼容性。
-
&ngx_core_module_ctx
模块上下文结构体,定义模块的生命周期回调函数(如配置解析、进程初始化等)。对于 ngx_core_module
,其上下文主要处理全局配置的创建和合并。
-
ngx_core_commands
模块支持的配置指令列表,例如 daemon
、worker_processes
、pid
等全局配置项。这些指令在 Nginx 配置文件中定义,由该模块解析。
-
NGX_CORE_MODULE
模块类型标识,表明这是一个核心模块(Core Module),负责处理全局配置和基础功能。其他模块类型包括 NGX_HTTP_MODULE
(HTTP 功能)、NGX_EVENT_MODULE
(事件处理)等。
Ubuntu 下 nginx-1.24.0 源码分析 - ngx_modules-CSDN博客
src\core\ngx_module.h 中
#define NGX_MODULE_V1 \
NGX_MODULE_UNSET_INDEX, NGX_MODULE_UNSET_INDEX, \
NULL, 0, 0, nginx_version, NGX_MODULE_SIGNATURE
#define NGX_MODULE_V1_PADDING 0, 0, 0, 0, 0, 0, 0, 0
NGX_MODULE_V1 用来填充
ngx_module_s的 ctx 前的字段
NGX_MODULE_V1_PADDING 用来填充
ngx_module_s 的最后几个字段
ngx_core_module_ctx-CSDN博客
ngx_core_module
的主要职责是管理 Nginx 的全局配置和核心行为,具体包括:
(1) 全局配置解析
-
通过 ngx_core_commands
解析 Nginx 主配置文件(如 nginx.conf
)中的全局指令
(2) 进程管理
-
虽然 ngx_core_module
的回调函数(如 init_master
、init_process
)大多为 NULL
,但它通过其他机制参与进程管理:
-
调用 ngx_init_signals
初始化信号处理。
-
创建主进程(Master Process)和工作进程(Worker Processes)。
-
管理进程间通信(IPC)和资源分配。
(3) 全局资源初始化
-
在 Nginx 启动阶段,负责初始化全局资源,例如:
-
内存池(Memory Pool)。
-
日志系统(Logging)。
-
基础数据结构(如循环链表、哈希表)。
总结
ngx_core_module
是 Nginx 的核心模块,负责全局配置解析、进程管理和基础资源初始化。它是 Nginx 模块化架构的根基,为其他功能模块(如 HTTP、事件处理)提供运行环境和支持。理解该模块的设计有助于深入掌握 Nginx 的启动流程、配置管理和扩展机制。