概述
在前面的文章中《Nginx 事件模块》介绍了Nginx 的事件驱动框架以及不同类型事件驱动模块的管理。本节基于前面的知识,简单介绍下在Linux 系统下的 epoll 事件驱动模块。关于 epoll 的使用与原理可以参照文章 《epoll 解析》。在这里直接介绍Nginx 服务器基于事件驱动框架实现的 epoll 事件驱动模块。
ngx_epoll_module 事件驱动模块
ngx_epoll_conf_t 结构体
ngx_epoll_conf_t 结构体是保存ngx_epoll_module 事件驱动模块的配置项结构。该结构体在文件src/event/modules/ngx_epoll_module.c 中定义:
/* 存储epoll模块配置项结构体 */
typedef struct {
ngx_uint_t events; /* 表示epoll_wait函数返回的最大事件数 */
ngx_uint_t aio_requests; /* 并发处理异步IO事件个数 */
} ngx_epoll_conf_t;
ngx_epoll_module 事件驱动模块的定义
所有模块的定义都是基于模块通用接口 ngx_module_t 结构,ngx_epoll_module 模块在文件src/event/modules/ngx_epoll_module.c 中定义如下:
/* epoll模块定义 */
ngx_module_t ngx_epoll_module = {
NGX_MODULE_V1,
&ngx_epoll_module_ctx, /* module context */
ngx_epoll_commands, /* module directives */
NGX_EVENT_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_epoll_module 模块的定义中,其中定义了该模块感兴趣的配置项ngx_epoll_commands 数组,该配置项数组在文件 src/event/modules/ngx_epoll_module.c 中定义:
/* 定义epoll模块感兴趣的配置项结构数组 */
static ngx_command_t ngx_epoll_commands[] = {
/*
* epoll_events配置项表示epoll_wait函数每次返回的最多事件数(即第3个参数),
* 在ngx_epoll_init函数中会预分配epoll_events配置项指定的epoll_event结构体;
*/
{ ngx_string("epoll_events"),
NGX_EVENT_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
0,
offsetof(ngx_epoll_conf_t, events),
NULL },
/*
* 该配置项表示创建的异步IO上下文能并发处理异步IO事件的个数,
* 即io_setup函数的第一个参数;
*/
{ ngx_string("worker_aio_requests"),
NGX_EVENT_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
0,
offsetof(ngx_epoll_conf_t, aio_requests),
NULL },
ngx_null_command
};
在 ngx_epoll_module 模块的定义中,定义了该模块的上下文结构ngx_epoll_module_ctx,该上下文结构是基于事件模块的通用接口ngx_event_module_t 结构来定义的。该上下文结构在文件src/event/modules/ngx_epoll_module.c 中定义:
/* 由事件模块通用接口ngx_event_module_t定义的epoll模块上下文结构 */
ngx_event_module_t ngx_epoll_module_ctx = {
&epoll_name,
ngx_epoll_create_conf, /* create configuration */
ngx_epoll_init_conf, /* init configuration */
{
ngx_epoll_add_event, /* add an event */
ngx_epoll_del_event, /* delete an event */
ngx_epoll_add_event, /* enable an event */
ngx_epoll_del_event, /* disable an event */
ngx_epoll_add_connection, /* add an connection */
ngx_epoll_del_connection, /* delete an connection */
NULL, /* process the changes */
ngx_epoll_process_events, /* process the events */
ngx_epoll_init, /* init the events */
ngx_epoll_done, /* done the events */
}
};
在 ngx_epoll_module 模块的上下文事件接口结构中,重点定义了ngx_event_actions_t 结构中的接口回调方法。
ngx_epoll_module 事件驱动模块的操作
ngx_epoll_module 模块的操作由ngx_epoll_module 模块的上下文事件接口结构中成员actions 实现。该成员实现的方法如下所示:
ngx_epoll_add_event, /* add an event */
ngx_epoll_del_event, /* delete an event */
ngx_epoll_add_event, /* enable an event */
ngx_epoll_del_event, /* disable an event */
ngx_epoll_add_connection, /* add an connection */
ngx_epoll_del_connection, /* delete an connection */
NULL, /* process the changes */
ngx_epoll_process_events,