操作系统 / 系统课时
用定时器清理空闲连接
用定时器清理空闲连接
长连接如果没有空闲回收策略,客户端断网、NAT 状态丢失或业务忘记主动关闭时,服务器会长期保留文件描述符和连接对象。本篇把 Linux timerfd 接入 epoll,为连接记录最近活动时间,并周期性批量扫描超时连接,让清理逻辑与普通 I/O 事件处在同一个事件循环中。
学习目标
- 用单调时钟记录连接活动时间,避免系统时间校准影响超时判断。
- 使用
timerfd周期性唤醒epoll,批量检查并关闭空闲连接。 - 评估扫描周期、超时精度和大连接规模下的复杂度取舍。
空闲超时需要两个时间尺度
每个连接保存 last_activity,表示最近一次有效活动发生的单调时间。事件循环另外维护一个周期定时器,例如每 5 秒触发一次;触发时计算 now - last_activity,超过 30 秒的连接就关闭。
这里有两个不同参数:空闲超时决定连接最多可以多久没有活动,扫描周期决定服务器多久检查一次。因此关闭动作最多会比阈值再晚一个扫描周期。若要求 30 秒超时且误差不能超过 1 秒,扫描周期就不能设成 10 秒。

把 timerfd 放进 epoll
下面的服务器把 timerfd 和监听套接字一起注册到 epoll。本例把“成功读取客户端数据”定义为活动;如果你的协议把服务器主动推送也视为活动,应在成功发送后同步更新 last_activity。
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#define PORT 9091
#define MAX_EVENTS 64
#define IDLE_TIMEOUT_SEC 30
#define SCAN_INTERVAL_SEC 5
typedef struct Conn {
int fd;
double last_activity;
struct Conn *prev;
struct Conn *next;
} Conn;
static int epfd;
static Conn *head;
static int listener_tag;
static int timer_tag;
static double monotonic_now(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec / 1000000000.0;
}
static void add_conn(Conn *c) {
c->next = head;
if (head) head->prev = c;
head = c;
}
static void close_conn(Conn *c, const char *reason) {
printf("fd=%d %s\n", c->fd, reason);
epoll_ctl(epfd, EPOLL_CTL_DEL, c->fd, NULL);
close(c->fd);
if (c->prev) c->prev->next = c->next;
else head = c->next;
if (c->next) c->next->prev = c->prev;
free(c);
}
static void scan_idle_connections(void) {
double now = monotonic_now();
for (Conn *c = head, *next; c; c = next) {
next = c->next;
if (now - c->last_activity >= IDLE_TIMEOUT_SEC) {
close_conn(c, "idle timeout, closing");
}
}
}
static int handle_client_read(Conn *c) {
char buf[4096];
for (;;) {
ssize_t n = recv(c->fd, buf, sizeof(buf), 0);
if (n > 0) {
c->last_activity = monotonic_now();
printf("fd=%d activity\n", c->fd);
} else if (n == 0) {
return -1;
} else if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
} else {
return -1;
}
}
}
int main(void) {
int lfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
int one = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(PORT),
.sin_addr.s_addr = htonl(INADDR_LOOPBACK)
};
if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) < 0 || listen(lfd, 128) < 0) {
perror("listen");
return 1;
}
int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
struct itimerspec its = {
.it_interval = {.tv_sec = SCAN_INTERVAL_SEC},
.it_value = {.tv_sec = SCAN_INTERVAL_SEC}
};
if (tfd < 0 || timerfd_settime(tfd, 0, &its, NULL) < 0) {
perror("timerfd");
return 1;
}
epfd = epoll_create1(EPOLL_CLOEXEC);
struct epoll_event lev = {.events = EPOLLIN, .data.ptr = &listener_tag};
struct epoll_event tev = {.events = EPOLLIN, .data.ptr = &timer_tag};
epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &lev);
epoll_ctl(epfd, EPOLL_CTL_ADD, tfd, &tev);
printf("listening on 127.0.0.1:%d, idle=%ds, scan=%ds\n",
PORT, IDLE_TIMEOUT_SEC, SCAN_INTERVAL_SEC);
struct epoll_event events[MAX_EVENTS];
for (;;) {
int nready = epoll_wait(epfd, events, MAX_EVENTS, -1);
int timer_fired = 0;
for (int i = 0; i < nready; i++) {
void *tag = events[i].data.ptr;
if (tag == &listener_tag) {
for (;;) {
int cfd = accept4(lfd, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (cfd < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
perror("accept4");
return 1;
}
Conn *c = calloc(1, sizeof(*c));
c->fd = cfd;
c->last_activity = monotonic_now();
add_conn(c);
struct epoll_event cev = {
.events = EPOLLIN | EPOLLRDHUP,
.data.ptr = c
};
epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &cev);
printf("client fd=%d connected\n", cfd);
}
} else if (tag == &timer_tag) {
uint64_t expirations;
if (read(tfd, &expirations, sizeof(expirations)) == sizeof(expirations)) {
timer_fired = 1;
}
} else {
Conn *c = tag;
uint32_t e = events[i].events;
if ((e & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) ||
((e & EPOLLIN) && handle_client_read(c) < 0)) {
close_conn(c, "peer closed");
}
}
}
/* 先处理完本轮 I/O 事件,再释放空闲连接,避免 events 中留下悬空指针。 */
if (timer_fired) scan_idle_connections();
}
}预期结果
listening on 127.0.0.1:9091, idle=30s, scan=5s
client fd=<ID> connected
fd=<ID> activity
fd=<ID> idle timeout, closing<ID> 是运行时分配的文件描述符,实际值会不同。连接若持续发送数据,last_activity 会不断刷新;停止活动后,它会在达到 30 秒后的某次 5 秒扫描中被关闭。
为什么要用 CLOCK_MONOTONIC
空闲超时比较的是“经过了多久”,而不是“现在是几点”。CLOCK_REALTIME 可能因为 NTP 校时或管理员修改系统时间而跳变,导致连接提前或延后过期;CLOCK_MONOTONIC 只随系统运行向前推进,更适合计算持续时间。
读取 timerfd 也不能省略。计时器到期后内核会把到期次数累积在描述符中;只有读出这个计数,可读状态才会被清除。事件循环如果只扫描连接却不 read(),会因为 timerfd 持续可读而形成忙循环。
控制批量扫描的成本
每次定时器触发都遍历全部连接,时间复杂度是 。对几千或几万连接,这种方案通常简单且容易验证;如果连接达到更大规模、扫描周期又很短,周期性全量遍历会变成明显的 CPU 峰值。
这时可以把连接按到期时间组织到最小堆、时间轮或分桶队列中,只处理当前应该过期的部分。但无论换成哪种结构,核心约束不变:活动时间必须使用同一时间源更新,关闭连接时必须同步从 epoll 和连接索引中移除,并确保后续事件不会再访问已经释放的连接对象。