1 定义
ngx_free_connection 函数 定义在 ./nginx-1.24.0/src/core/ngx_connection.c
voidngx_free_connection(ngx_connection_t*c){c->data=ngx_cycle->free_connections;ngx_cycle->free_connections=c;ngx_cycle->free_connection_n++;if(ngx_cycle->files&&ngx_cycle->files[c->fd]==c){ngx_cycle->files[c->fd]=NULL;}}
ngx_free_connection 函数的作用是 将已使用完毕的 `ngx_connection_t` 结构体归还到全局空闲连接链表中,以便后续复用, 同时清理该结构在文件描述符映射表中的记录。 该函数只回收连接结构体本身,不关闭底层的文件描述符(fd 需事先由其他逻辑关闭)。
2 详解
1 函数签名
voidngx_free_connection(ngx_connection_t*c)
返回类型 void 函数执行完毕后不向调用者返回任何值
参数 ngx_connection_t *c 指向本次要处理的连接
2 逻辑流程
1 将连接结构体 c 插入空闲链表头部 2 清理文件描述符映射表
1 将连接结构体 c 插入空闲链表头部
{c->data=ngx_cycle->free_connections;ngx_cycle->free_connections=c;ngx_cycle->free_connection_n++;
将当前全局空闲链表头指针,存入待释放连接 c 的 data 字段 将全局空闲链表头指针更新为当前正在释放的连接 c 完成链表头插操作:新归还的节点 c 成为链表的第一个节点,原链表挂在它的 data 后面 将全局空闲连接计数器加 1
2 清理文件描述符映射表
if(ngx_cycle->files&&ngx_cycle->files[c->fd]==c){ngx_cycle->files[c->fd]=NULL;}}
检查文件描述符映射表中该连接对应的条目是否仍然有效且恰指向 c 本身 将 files 数组中该 fd 对应的指针设置为 NULL,切断映射关系 连接被归还到空闲池后,其 fd 通常已被关闭 此时 files[fd] 已无实际用途,必须清空,否则保留悬垂指针