操作系统 / 系统课时
补齐缓冲、背压与超时机制
补齐缓冲、背压与超时机制
只有 epoll 主循环还不足以应对真实流量:请求可能被拆成半包,响应可能只写出一部分,慢客户端还会长期占住连接和内存。本节把输入分帧、输出缓冲、高低水位背压和空闲超时合进同一个可运行服务器,并用三类客户端验证稳定性。
学习目标
- 用输入缓冲跨多次
recv保存半包,只在完整分隔符到达后解析请求。 - 用输出缓冲和
EPOLLOUT处理部分写,并通过高低水位暂停与恢复EPOLLIN。 - 使用单调时钟实现空闲超时,限制停止读写的连接长期占用资源。
三类故障来自同一条数据链
半包发生在“内核接收缓冲区到应用输入缓冲”之间;部分写发生在“应用输出缓冲到内核发送缓冲”之间;慢客户端则让输出缓冲持续堆积。如果继续无条件读取新请求,单个连接就可能把进程内存拖满,因此背压必须和输入、输出事件订阅联动。

示例协议故意保持简单:PING\n 返回 PONG\n;BIG n\n 返回 n 个 X 再加换行,且 n 最大 1 MiB。它足以制造半包、大响应和慢读场景,又不会把教学重点转移到复杂业务协议。
集成输入缓冲、输出缓冲和超时
连接使用 8 KiB 输入缓冲保存尚未成帧的数据,输出缓冲按需扩容但限制在 2 MiB。待发送数据达到 256 KiB 后暂停读事件,降到 64 KiB 后再恢复,形成回差,避免事件订阅在临界值附近频繁抖动。
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#define MAX_EVENTS 256
#define MAX_FD 65536
#define IN_CAP 8192
/* 高低水位形成回差,避免 EPOLLIN 在临界点频繁开关。 */
#define HIGH_WATER (256 * 1024)
#define LOW_WATER (64 * 1024)
#define MAX_PENDING (2 * 1024 * 1024)
/* 演示把空闲超时压到 5 秒,生产应按协议和业务延迟预算调整。 */
#define IDLE_MS 5000
typedef struct {
int fd;
char in[IN_CAP];
size_t in_len;
char *out;
size_t out_off;
size_t out_len;
size_t out_cap;
uint64_t last_active_ms;
bool read_paused;
bool peer_eof;
} Conn;
/* 演示用 fd 索引连接;生产可换成更紧凑的连接表或 slab。 */
static Conn *conns[MAX_FD];
static uint64_t now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static size_t pending(const Conn *c) {
return c->out_len - c->out_off;
}
static void close_conn(int epfd, int fd, const char *reason) {
Conn *c = (fd >= 0 && fd < MAX_FD) ? conns[fd] : NULL;
if (!c) return;
printf("close fd=%d reason=%s pending=%zu\n", fd, reason, pending(c));
epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
close(fd);
free(c->out);
free(c);
conns[fd] = NULL;
}
static int mod_events(int epfd, Conn *c) {
struct epoll_event ev = {0};
ev.events = EPOLLRDHUP;
if (!c->read_paused && !c->peer_eof) ev.events |= EPOLLIN;
if (pending(c) > 0) ev.events |= EPOLLOUT;
ev.data.fd = c->fd;
return epoll_ctl(epfd, EPOLL_CTL_MOD, c->fd, &ev);
}
static int ensure_out(Conn *c, size_t extra) {
size_t left = pending(c);
if (left + extra > MAX_PENDING) return -1;
/* 已发送前缀不再需要;空间不足时先压紧,减少反复扩容。 */
if (c->out_off > 0 && (c->out_cap - c->out_len < extra)) {
memmove(c->out, c->out + c->out_off, left);
c->out_off = 0;
c->out_len = left;
}
if (c->out_cap - c->out_len >= extra) return 0;
size_t need = c->out_len + extra;
size_t cap = c->out_cap ? c->out_cap : 4096;
while (cap < need) cap *= 2;
if (cap > MAX_PENDING) cap = MAX_PENDING;
char *p = realloc(c->out, cap);
if (!p) return -1;
c->out = p;
c->out_cap = cap;
return 0;
}
static int queue_bytes(Conn *c, const void *data, size_t len) {
if (ensure_out(c, len) == -1) return -1;
memcpy(c->out + c->out_len, data, len);
c->out_len += len;
if (pending(c) >= HIGH_WATER) c->read_paused = true;
return 0;
}
static int queue_big(Conn *c, size_t n) {
if (ensure_out(c, n + 1) == -1) return -1;
memset(c->out + c->out_len, 'X', n);
c->out_len += n;
c->out[c->out_len++] = '\n';
if (pending(c) >= HIGH_WATER) c->read_paused = true;
return 0;
}
static int process_lines(Conn *c) {
/* 协议以换行分帧:半包先留在输入缓冲,只处理完整请求。 */
for (;;) {
char *nl = memchr(c->in, '\n', c->in_len);
if (!nl) return c->in_len == IN_CAP ? -1 : 0;
size_t line_len = (size_t)(nl - c->in);
char line[128];
if (line_len >= sizeof(line)) return -1;
memcpy(line, c->in, line_len);
line[line_len] = '\0';
size_t consumed = line_len + 1;
memmove(c->in, c->in + consumed, c->in_len - consumed);
c->in_len -= consumed;
if (strcmp(line, "PING") == 0) {
if (queue_bytes(c, "PONG\n", 5) == -1) return -1;
} else if (strncmp(line, "BIG ", 4) == 0) {
char *end = NULL;
unsigned long n = strtoul(line + 4, &end, 10);
if (!end || *end != '\0' || n == 0 || n > 1024 * 1024)
return -1;
if (queue_big(c, (size_t)n) == -1) return -1;
} else {
if (queue_bytes(c, "ERR\n", 4) == -1) return -1;
}
if (c->read_paused) return 0;
}
}
static int handle_read(int epfd, Conn *c) {
/* 输出积压达到高水位后停止读取,让 TCP 接收窗口自然形成背压。 */
while (!c->read_paused) {
ssize_t n = recv(c->fd, c->in + c->in_len, IN_CAP - c->in_len, 0);
if (n > 0) {
c->in_len += (size_t)n;
c->last_active_ms = now_ms();
if (process_lines(c) == -1) return -1;
continue;
}
if (n == 0) {
c->peer_eof = true;
break;
}
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
return -1;
}
if (mod_events(epfd, c) == -1) return -1;
return c->peer_eof && pending(c) == 0 ? 1 : 0;
}
static int handle_write(int epfd, Conn *c) {
/* 非阻塞 send 可能只写一部分;未发送数据继续保留并监听 EPOLLOUT。 */
while (pending(c) > 0) {
ssize_t n = send(c->fd, c->out + c->out_off, pending(c), MSG_NOSIGNAL);
if (n > 0) {
c->out_off += (size_t)n;
c->last_active_ms = now_ms();
continue;
}
if (n == -1 && errno == EINTR) continue;
if (n == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) break;
return -1;
}
if (pending(c) == 0) c->out_off = c->out_len = 0;
if (c->read_paused && pending(c) <= LOW_WATER) {
/* 降到低水位再恢复读取,并先消费应用层输入缓冲里已成帧的数据。 */
c->read_paused = false;
if (process_lines(c) == -1) return -1;
}
if (mod_events(epfd, c) == -1) return -1;
return c->peer_eof && pending(c) == 0 ? 1 : 0;
}
static int add_conn(int epfd, int fd) {
if (fd < 0 || fd >= MAX_FD) return -1;
Conn *c = calloc(1, sizeof(*c));
if (!c) return -1;
c->fd = fd;
c->last_active_ms = now_ms();
int sndbuf = 32768; /* 仅为演示 partial write;生产按吞吐与内存预算调优。 */
setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
struct epoll_event ev = { .events = EPOLLIN | EPOLLRDHUP, .data.fd = fd };
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1) {
free(c);
return -1;
}
conns[fd] = c;
return 0;
}
static void accept_all(int epfd, int lfd) {
for (;;) {
int cfd = accept4(lfd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (cfd >= 0) {
if (add_conn(epfd, cfd) == -1) close(cfd);
continue;
}
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) return;
perror("accept4");
return;
}
}
static void expire_idle(int epfd) {
/* 演示按秒扫描;超大连接规模应改为最小堆或时间轮。 */
uint64_t now = now_ms();
for (int fd = 0; fd < MAX_FD; fd++) {
Conn *c = conns[fd];
if (c && now - c->last_active_ms >= IDLE_MS)
close_conn(epfd, fd, "idle timeout");
}
}
int main(int argc, char **argv) {
int port = argc == 2 ? atoi(argv[1]) : 8080;
int lfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (lfd == -1) { perror("socket"); return 1; }
int one = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_ANY),
.sin_port = htons((uint16_t)port)
};
if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) == -1 ||
listen(lfd, SOMAXCONN) == -1) {
perror("bind/listen");
return 1;
}
int epfd = epoll_create1(EPOLL_CLOEXEC);
if (epfd == -1) { perror("epoll_create1"); return 1; }
struct epoll_event lev = { .events = EPOLLIN | EPOLLET, .data.fd = lfd };
if (epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &lev) == -1) {
perror("epoll_ctl");
return 1;
}
printf("listening on 0.0.0.0:%d idle=%dms\n", port, IDLE_MS);
struct epoll_event events[MAX_EVENTS];
for (;;) {
int n = epoll_wait(epfd, events, MAX_EVENTS, 1000);
if (n == -1) {
if (errno == EINTR) continue;
perror("epoll_wait");
return 1;
}
for (int i = 0; i < n; i++) {
int fd = events[i].data.fd;
uint32_t e = events[i].events;
if (fd == lfd) {
accept_all(epfd, lfd);
continue;
}
Conn *c = (fd >= 0 && fd < MAX_FD) ? conns[fd] : NULL;
if (!c) continue;
if (e & EPOLLERR) {
close_conn(epfd, fd, "socket error");
continue;
}
if (e & (EPOLLIN | EPOLLRDHUP)) {
int rc = handle_read(epfd, c);
if (rc < 0) {
close_conn(epfd, fd, "read/protocol error");
continue;
}
if (rc > 0) {
close_conn(epfd, fd, "peer closed");
continue;
}
}
c = conns[fd];
if (c && (e & EPOLLOUT)) {
int rc = handle_write(epfd, c);
if (rc < 0) close_conn(epfd, fd, "write error");
else if (rc > 0) close_conn(epfd, fd, "peer closed");
}
c = conns[fd];
if (c && (e & EPOLLHUP)) close_conn(epfd, fd, "hangup");
}
expire_idle(epfd);
}
}预期结果:保存为 epoll_stable.c 后可在 Linux 上编译。连接采用水平触发的 EPOLLIN/EPOLLOUT,监听 fd 仍用 EPOLLET 并把 accept4 消费到 EAGAIN;5 秒空闲阈值只为便于实验,生产值应按协议心跳、请求时延和资源预算调整。
运行服务并验证三条边界
先编译并启动服务器。示例把已接受 socket 的发送缓冲调小到 32 KiB,只是为了更容易稳定复现 partial write;生产环境不应机械照抄这个值。
gcc -std=c11 -O2 -Wall -Wextra -Werror epoll_stable.c -o epoll_stable
./epoll_stable 8080预期输出
listening on 0.0.0.0:<PORT> idle=5000ms再在另一个终端运行测试客户端。第一条请求分两次发送,验证半包不会被提前解析;第二条读取 300000 字节大响应;第三条把接收缓冲设小并暂停读取 7 秒,验证服务器最终主动回收慢连接。
python3 - <<'PY'
import socket
import time
ADDR = ("127.0.0.1", 8080)
def read_line(sock):
data = bytearray()
while not data.endswith(b"\n"):
chunk = sock.recv(65536)
if not chunk:
break
data.extend(chunk)
return bytes(data)
s = socket.create_connection(ADDR)
s.sendall(b"PI")
time.sleep(0.1)
s.sendall(b"NG\n")
print("half:", read_line(s).decode().strip())
s.close()
s = socket.create_connection(ADDR)
s.sendall(b"BIG 300000\n")
data = read_line(s)
print("big:", len(data), data[-1:] == b"\n")
s.close()
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
s.connect(ADDR)
s.sendall(b"BIG 1048576\n")
time.sleep(7)
s.settimeout(2)
received = 0
closed = False
try:
while True:
chunk = s.recv(65536)
if not chunk:
closed = True
break
received += len(chunk)
except socket.timeout:
pass
print("slow closed:", closed, "received:", received)
s.close()
PY预期输出
half: PONG
big: 300001 True
slow closed: True received: <BYTES><BYTES> 受 TCP 接收窗口、发送缓冲和本机内核实现影响,实际值可能不同;关键判据是 slow closed: True。服务器终端还应出现一条 reason=idle timeout 的关闭日志,其中 fd 和 pending 字节数同样是动态值。
背压不是简单拒绝请求
高水位达到后,程序不是立即关闭连接,而是从该 fd 的 epoll 兴趣集中移除 EPOLLIN,让应用停止继续消费请求。客户端继续发送时,内核接收缓冲逐渐填满,TCP 接收窗口收缩,压力最终沿网络回传给发送方。这个链路才是“背压”,而不是在用户态无限缓存后再报错。
当输出降到低水位时再恢复 EPOLLIN,可以避免 pending 在 256 KiB 附近上下波动时不断 epoll_ctl。恢复读取前,示例还会先处理输入缓冲里已经完整成帧的请求,否则这些数据已经离开内核,未必还会产生新的可读事件。
超时与内存上限必须一起存在
只设置输出上限而没有超时,攻击者仍可以建立大量连接后长期不动;只设置超时而没有输出上限,单个连接又可能在超时窗口内堆积过多内存。示例同时限制每连接 pending 不超过 2 MiB,并用 CLOCK_MONOTONIC 记录最后一次成功读写时间,避免系统时间被校准时影响超时判断。
能够通过半包、大响应和停止读取这三项测试,才说明事件循环不只是“能收连接”,而是已经具备基本的流式协议边界、非阻塞写入和资源自我保护能力。