1 定义ngx_epoll_del_connection 函数 定义在 ./nginx-1.24.0/src/event/modules/ngx_epoll_module.cstaticngx_int_tngx_epoll_del_connection(ngx_connection_t*c,ngx_uint_tflags){intop;structepoll_eventee;/* * when the file descriptor is closed the epoll automatically deletes * it from its queue so we do not need to delete explicitly the event * before the closing the file descriptor */if(flagsNGX_CLOSE_EVENT){c-read-active0;c-write-active0;returnNGX_OK;}ngx_log_debug1(NGX_LOG_DEBUG_EVENT,c-log,0,epoll del connection: fd:%d,c-fd);opEPOLL_CTL_DEL;ee.events0;ee.data.ptrNULL;if(epoll_ctl(ep,op,c-fd,ee)-1){ngx_log_error(NGX_LOG_ALERT,c-log,ngx_errno,epoll_ctl(%d, %d) failed,op,c-fd);returnNGX_ERROR;}c-read-active0;c-write-active0;returnNGX_OK;}ngx_epoll_del_connection 函数的作用是 从 epoll 监听队列中移除指定连接的事件。 若调用时带有 NGX_CLOSE_EVENT 标志通常表示即将关闭连接 则只将连接的读写事件标记为不活跃不执行系统调用 依赖内核在 close(fd) 时自动清理 否则显式调用 epoll_ctl(EPOLL_CTL_DEL) 删除事件并更新事件状态为不活跃。2 详解1 函数签名staticngx_int_tngx_epoll_del_connection(ngx_connection_t*c,ngx_uint_tflags)返回值 成功返回 NGX_OK 失败返回 NGX_ERROR参数1 ngx_connection_t *c 本次待处理的连接 参数2 ngx_uint_t flags 调用者可以通过位掩码向函数传递额外控制信息2 逻辑流程1 局部变量 2 NGX_CLOSE_EVENT 情况 3 参数设置 4 调用 epoll_ctl 5 active 标记置 0 6 返回成功状态1 局部变量{intop;structepoll_eventee;2 NGX_CLOSE_EVENT 情况/* * when the file descriptor is closed the epoll automatically deletes * it from its queue so we do not need to delete explicitly the event * before the closing the file descriptor */if(flagsNGX_CLOSE_EVENT){c-read-active0;c-write-active0;returnNGX_OK;}判断 flags 参数中是否包含 NGX_CLOSE_EVENT 标志位。 flags NGX_CLOSE_EVENT 进行按位与运算 结果为非零时表示该标志被置位条件成立 即当前的“删除”操作是因为连接即将关闭而被调用。 这是两条处理路径的分岔点 如果连接要关闭就走快速路径仅修改状态不做系统调用 否则走完整删除流程。 将连接中读事件结构的 active 标志清 0 同样将写事件的 active 标志清 0 函数结束向调用者返回成功状态。3 参数设置ngx_log_debug1(NGX_LOG_DEBUG_EVENT,c-log,0,epoll del connection: fd:%d,c-fd);调试日志opEPOLL_CTL_DEL;ee.events0;ee.data.ptrNULL;#1 将 op 变量赋值为 epoll 删除事件的操作码#2 将 ee 结构体中的 events 字段设为 0。 events 是一个位掩码用于描述关注的事件类型。 对于 EPOLL_CTL_DEL 操作内核不需要关心该字段的具体值完全忽略 但设为 0 是最佳实践消除不确定内容。#3 将 ee 结构体中的 data.ptr 指针设为 NULL。 data 是一个联合体在添加事件时通常保存关联的上下文指针如指向 ngx_connection_t。 删除时内核不再需要该信息设为 NULL 可避免留下悬空指针。 意义保持结构体内部干净杜绝通过该指针意外访问已释放内存的风险。4 调用 epoll_ctlif(epoll_ctl(ep,op,c-fd,ee)-1){ngx_log_error(NGX_LOG_ALERT,c-log,ngx_errno,epoll_ctl(%d, %d) failed,op,c-fd);returnNGX_ERROR;}调用 epoll_ctl 执行真实的 epoll 事件删除并判断是否失败5 active 标记置 0c-read-active0;c-write-active0;active 标记置 06 返回成功状态returnNGX_OK;}