Ubuntu 下 nginx-1.24.0 源码分析 - ngx_buf_t
ngx_buf_t
定义在
src/core/ngx_buf.h
typedef struct ngx_buf_s ngx_buf_t;
struct ngx_buf_s {
u_char *pos;
u_char *last;
off_t file_pos;
off_t file_last;
u_char *start; /* start of buffer */
u_char *end; /* end of buffer */
ngx_buf_tag_t tag;
ngx_file_t *file;
ngx_buf_t *shadow;
/* the buf's content could be changed */
unsigned temporary:1;
/*
* the buf's content is in a memory cache or in a read only memory
* and must not be changed
*/
unsigned memory:1;
/* the buf's content is mmap()ed and must not be changed */
unsigned mmap:1;
unsigned recycled:1;
unsigned in_file:1;
unsigned flush:1;
unsigned sync:1;
unsigned last_buf:1;
unsigned last_in_chain:1;
unsigned last_shadow:1;
unsigned temp_file:1;
/* STUB */ int num;
};
ngx_buf_s
是 Nginx 中用于管理缓冲区的核心结构体,主要用于处理网络 I/O 和文件操作。它通过灵活的标志位和指针设计,支持内存、文件、mmap 等多种数据源的高效处理。以下是对其成员的详细解释:
结构体成员详解
-
u_char *pos
和u_char *last
- 作用:标记内存缓冲区中有效数据的起始和结束位置。
- 细节:
pos
指向当前待处理数据的起始位置。last
指向有效数据的末尾(最后一个字节的下一个位置)。- 通过移动这两个指针,可以高效地管理缓冲区的读写进度。
-
off_t file_pos
和off_t file_last
- 作用:当缓冲区关联文件时,标记文件中的起始和结束偏移量。
- 细节:
- 用于直接操作文件(如
sendfile
系统调用),避免将文件数据加载到内存。 - 例如,发送文件的某一部分时,
file_pos
和file_last
定义文件的范围。
- 用于直接操作文件(如
-
u_char *start
和u_char *end
- 作用:定义整个缓冲区的内存边界。
- 细节:
start
是缓冲区内存的起始地址。end
是缓冲区内存的结束地址(最后一个字节的下一个位置)。- 用于防止越界访问,确保
pos
和last
在合法范围内移动。
-
ngx_buf_tag_t tag
- 作用:标识缓冲区的类型或所属模块。
- 细节:
- 通常用于调试或模块间协作,例如标记缓冲区由哪个模块创建或管理。
-
ngx_file_t *file
- 作用:指向关联的文件对象。
- 细节:
- 当缓冲区表示文件数据时,通过此指针访问文件描述符和元数据。
-
ngx_buf_t *shadow
- 作用:指向另一个缓冲区,形成链式引用。
- 细节:
- 用于共享或引用其他缓冲区的数据,避免内存拷贝。
- 例如,当需要修改缓冲区数据时,可能创建一个
shadow
缓冲区来保存原始数据。
-
位字段标志(unsigned 类型,1 位)
temporary
:缓冲区内容可修改(如临时内存)。memory
:数据在只读内存或内存缓存中,不可修改。mmap
:数据通过mmap
映射自文件,不可修改。recycled
:缓冲区可被回收或重用。in_file
:数据存储在文件中(需结合file
、file_pos
等字段)。flush
:立即刷新缓冲区(如强制发送数据)。sync
:需要同步操作(如处理完缓冲区后触发事件)。last_buf
:链中的最后一个缓冲区(如 HTTP 响应结束)。last_in_chain
:当前链的最后一个缓冲区(可能还有其他链)。last_shadow
:最后一个影子缓冲区(与shadow
配合使用)。temp_file
:关联的文件是临时文件(处理完可删除)。
-
int num
- 作用:占位符(STUB),可能用于调试或扩展。
典型应用场景
-
内存缓冲区:
pos
和last
定义有效数据范围,temporary
标志为 1,表示数据可修改。
-
文件传输:
in_file
标志为 1,file
指向文件对象,file_pos
和file_last
定义文件范围,结合sendfile
实现零拷贝。
-
复合缓冲区链:
- 多个
ngx_buf_t
通过链表连接,处理分散的数据(如 HTTP 响应头在内存,体在文件)。
- 多个
-
影子缓冲区:
- 通过
shadow
引用其他缓冲区,避免数据拷贝,例如在过滤链中保留原始数据。
- 通过