You are on page 1of 3

lighttpd-1.4.

20 源码分析

7 Chunk.c 源码分析
7.1 chunk 数据结构体定义
chunk 结构体内指定了两种块类型,一种是 MEM_CHUNK,一种是 FILE_CHUNK,对
于各自块类型给出了相应的数据保存结构字段。另外有个 next 字段可以将各个 chunk 结构
体连接起来组成链表。

typedef struct chunk {


enum { UNUSED_CHUNK, MEM_CHUNK, FILE_CHUNK } type;

buffer *mem; /* either the storage of the mem-chunk or the read-ahead buffer */

struct {
/* filechunk */
buffer *name; /* name of the file */
off_t start; /* starting offset in the file */
/*从 start 开始需要发送的字节数目*/
off_t length; /* octets to send from the starting offset *//*octet 就是 byte*/

int fd;
struct {
char *start; /* the start pointer of the mmap'ed area */
size_t length; /* size of the mmap'ed area */
off_t offset; /* start is <n> octet away from the start of the file */
} mmap;

int is_temp; /* file is temporary and will be deleted if on cleanup */


} file;

off_t offset; /* octets sent from this chunk


the size of the chunk is either
- mem-chunk: mem->used - 1
- file-chunk: file.length
*/

struct chunk *next;


} chunk;

chunkqueue 利用 chunk 组成一个数据结构体,该数据结构体包含两条链表,一条是将所


有正在被使用的块串联起来形成的链表(记录有该链表的头、尾),一条记录已经使用完毕
但还没有释放的块结构(仅记录链表头以及链表内块结构数目,最大数目为 5),这些块可
以看作是用作缓冲池被程序再次利用,避免反复的进行内存分配与释放,减少内存碎片,可
以认为其为内存池实现的一种方式。

讨论 QQ 群:45438969 邮箱:lenky0401@163.com 地址:重庆大学 A 区二舍 1


我心永恒 爱无止境
lighttpd-1.4.20 源码分析

typedef struct {
chunk *first;
chunk *last;

chunk *unused;
size_t unused_chunks;

array *tempdirs;

off_t bytes_in, bytes_out;


} chunkqueue;

7.2 chunkqueue 数据结构体操作


对于结构体 chunk 和 chunkqueue 的操作实现都比较简单,理解起来都没什么难点,下
面简单列出各个函数的功能。
函数名 功能
chunkqueue_init 初始化并返回一个 chunkqueue 结构体。
chunk_init 初始化并返回一个 chunk 结构体。
chunk_free 释放一个 chunk 结构体。
chunk_reset 重置一个 chunk 结构体。
chunkqueue_free 释放一个 chunkqueue 结构体。
chunkqueue_get_unused_chunk 从 chunkqueue 中获取一个未使用的 chunk,
如果没有,则新建立一个 chunk 并返回它。
chunkqueue_prepend_chunk 将一指定块添加到 chunkqueue 单链表表头。
chunkqueue_append_chunk 将一指定块添加到 chunkqueue 单链表表尾。
chunkqueue_reset 重置 chunkqueue。
chunkqueue_append_file 给 chunkqueue 增加一块 file 类型的 chunk 块
到尾部。
chunkqueue_append_buffer 给 chunkqueue 增加一块 mem 类型的 chunk
块到尾部,新增块内容为指定 buffer 的一个
拷贝。
chunkqueue_append_buffer_weak 给 chunkqueue 增加一块 mem 类型的 chunk
讨论 QQ 群:45438969 邮箱:lenky0401@163.com 地址:重庆大学 A 区二舍 2
我心永恒 爱无止境
lighttpd-1.4.20 源码分析

块到尾部,新增块内容为指定 buffer 的一个


引用。
chunkqueue_prepend_buffer 给 chunkqueue 增加一块 mem 类型的 chunk
块到头部,新增块内容为指定 buffer 的一个
拷贝。
chunkqueue_append_mem 给 chunkqueue 增加一块 mem 类型的 chunk
块到尾部,新增块内容为指定字符串的一个
子串。
chunkqueue_get_prepend_buffer 从 chunkqueue 中获取一块未使用的 mem 类
型 chunk 块并添加到 chunkqueue 头部。
chunkqueue_get_append_buffer 从 chunkqueue 中获取一块未使用的 mem 类
型 chunk 块并添加到 chunkqueue 尾部。
chunkqueue_set_tempdirs 设置 chunkqueue 结构字段 tempdirs。
chunkqueue_get_append_tempfile 建立临时目录,当建立不成功时,chunk 里的
file.fd 为-1。
chunkqueue_length 获取所有 chunk 块的字节长度,mem 长度+file
长度。
chunkqueue_written 获取所有 chunk 块的已写字节数。
chunkqueue_is_empty 检测 chunkqueue 是否为空。
chunkqueue_remove_finished_chunks 从链表头开始清理已经使用完毕的 chunk 块。

讨论 QQ 群:45438969 邮箱:lenky0401@163.com 地址:重庆大学 A 区二舍 3


我心永恒 爱无止境

You might also like