30 秒面试回答
连接需要一个明确拥有者,统一处理建立、I/O、关闭和回收。非阻塞 connect 不能见到可写就算成功,要检查 SO_ERROR。读 EOF 与写关闭分别记录,优雅关闭先拒绝新输出、排空待发数据,再关闭写方向并等待对端,整个过程有截止时间。事件和异步结果使用槽位加代次识别连接,避免 fd 复用后误操作新对象。
核心概念
内核 TCP 状态描述协议进度,应用状态还要管理输出队列、回调、认证和业务请求。draining 是本章的应用状态,表示停止接收新输出并等待已接受数据排空;它不等于某个 TCP FIN 状态。连接建立完成也只表示传输通道可用,应用握手或登录成功应有自己的条件。
本例规定单线程事件循环是 owner,只有它变更连接状态、使用或关闭 fd。工作线程若需要参与,只提交拥有值的结果和稳定 Handle,由 owner 处理。这样可串行化状态变化,但不能消除旧任务、旧事件或可重入回调带来的寿命问题。
fd、对象地址和应用 Handle 也有不同用途。fd 是当前系统资源编号,地址用于一次受控借用,Handle 是可重新验证的逻辑身份。本例 Handle 包含槽位和 generation;每次派发都核对槽内对象仍然存在,且代次相同。
原理深入
建立完成需要两层结果检查
非阻塞 TCP connect 立即返回零时连接完成;返回 EINPROGRESS 时保持 connecting,等待完成相关就绪,再读取 SO_ERROR。必须先检查 getsockopt 系统调用是否成功,再检查写入输出参数的错误值。就绪事件只提供检查机会,失败连接也可能产生可写或错误事件,见 connect(2) 和 getsockopt(2)。
SO_ERROR 会取出并清除挂起错误,定义见 socket(7)。由 owner 统一读取并记录结果,避免一个回调取走错误后,另一个回调把后续零值误解成原连接一直成功。若连接失败,关闭旧 socket,再按策略创建新的尝试;不要把失败后的 socket 状态当成可随意重用。
读方向结束与本地关闭计划分开
对于非零长度的流读取,收到 EOF 表示该接收方向的数据已结束,仍要检查应用解析器是否有截断帧,见 recv(2)。它不自动禁止本端发送。本例协议允许在读 EOF 后准备最后响应,显式请求关闭后才停止接受新输出。
begin_drain 进入 draining,pending 归零后执行 shutdown(SHUT_WR),成功后进入 write_closed。此时继续接收,直到 read_eof 为真或截止到达。读 EOF 先到和本地半关闭先到,两种顺序都必须处理;shutdown(2) 与 RFC 9293 §3.6.1 描述了两个方向的独立性。
本地 pending 归零只说明应用输出缓冲已交给本地发送路径。内核中可能仍有数据,对端也可能尚未执行业务。模型的 sent 事件表示一次已确认的本地字节进度,不是假设对端应用已经收到确认。
截止限制等待,不能代替调度
连接建立和关闭使用绝对截止时间。重复关闭请求最多缩短期限,不能每来一次请求就重新延长。真实等待采用单调时钟,EINTR 后重新计算剩余预算,不能从头再等完整超时。
模型只有收到 tick 事件才检查时间;owner 不处理事件时,状态不会自行清理。真实 poll 也受时间粒度和调度迟延影响,见 poll(2)。因此“配置两秒等待预算”和“程序一定在两秒内完成关闭”是不同承诺,后者不是本例提供的保证。
数据结构/系统内部实现
模型的单槽 Owner 保存 optional<Connection>、当前代次和退休标记。Connection 保存 fd 模型编号、阶段、pending、read_eof、截止及结束原因。pending 最大为 32,所有增加先检查剩余预算,进度事件不能消耗超过现有 pending 的字节。
| 阶段 | 接受新输出 | 下一步或结束条件 |
|---|---|---|
connecting | 否 | 检查过的连接结果决定 open 或错误;tick 可触发超时 |
open | 是,受容量限制 | 记录读 EOF;关闭请求进入 draining |
draining | 否 | 继续已有输出;归零后写半关闭,或错误/超时 |
write_closed | 否 | 等待读 EOF,或错误/超时 |
closed | 否 | 保存原因,回收对象,失效旧 Handle |
关闭动作先把对象标为 closed,关闭模型 fd 一次;apply 返回后 Owner 才 reset optional。它不会在正在执行的方法中销毁该对象。真实系统若允许用户回调重入,应进一步规定借用作用域和延迟回收,不能仅凭单线程就立即删除仍被调用栈引用的对象。
处理过一个事件后,同一批结果中可能仍有该连接的旧事件。epoll(7) 专门讨论事件缓存中的关闭问题。移除内核关注项和 close 不会把已经返回到用户态的条目凭空删除。派发时重新校验 Handle,可以拒绝旧事件和异步结果;若把已悬空的裸指针直接解引用,再去检查其中代次,顺序已经错了。
代次使用 uint64_t,仍是有限空间。本例在最大代次连接结束后将槽位退休,不回绕复用。正式系统可选择更换身份空间,或在确认所有旧任务和事件排空后重建,但需要相应证明。模型只模拟假 fd 42 的重复使用,不假设 Linux 必须按某个顺序分配编号。
C++ runnable demo
代码包含两个分开的验证层:model 中的状态机、假时间事件和记录动作,以及本机 loopback 上的真实非阻塞 TCP connect。模型的 close、shutdown 只记次数,不调用系统;真实部分不执行代次复用或优雅排空流程。
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <limits>
#include <optional>
#include <stdexcept>
#include <system_error>
#include <utility>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
namespace model {
using Tick = std::uint64_t;
enum class Phase { connecting, open, draining, write_closed, closed };
enum class Reason { none, graceful, connect_error, io_error, timeout };
enum class Kind { connect_result, enqueue, sent, peer_eof, begin_drain, tick, io_error };
struct Event { Kind kind; std::uint64_t value = 0; int error = 0; };
struct Handle { std::size_t slot; std::uint64_t generation; };
struct Snapshot {
Phase phase;
std::size_t pending;
bool read_eof;
};
// These actions are recorded, not syscalls. Fake fd numbers are never used by Linux.
struct Actions {
unsigned closes = 0;
unsigned shutdowns = 0;
int last_closed = -1;
bool fail_shutdown = false;
void close(int fd) noexcept { ++closes; last_closed = fd; }
bool shutdown_write(int) noexcept { ++shutdowns; return !fail_shutdown; }
};
class Connection {
Actions& actions_;
int fd_;
Phase phase_ = Phase::connecting;
std::size_t pending_ = 0;
bool read_eof_ = false;
Tick deadline_;
Reason reason_ = Reason::none;
void close_once(Reason reason) noexcept {
if (phase_ == Phase::closed) return;
phase_ = Phase::closed;
reason_ = reason;
actions_.close(std::exchange(fd_, -1));
}
void advance_close() noexcept {
if (phase_ == Phase::draining && pending_ == 0) {
if (!actions_.shutdown_write(fd_)) { close_once(Reason::io_error); return; }
phase_ = Phase::write_closed;
}
if (phase_ == Phase::write_closed && read_eof_) close_once(Reason::graceful);
}
public:
Connection(Actions& actions, int fd, Tick deadline) noexcept
: actions_(actions), fd_(fd), deadline_(deadline) {}
Connection(const Connection&) = delete;
Connection& operator=(const Connection&) = delete;
~Connection() { if (fd_ >= 0) actions_.close(std::exchange(fd_, -1)); }
bool apply(Event event) noexcept {
switch (event.kind) {
case Kind::connect_result:
if (phase_ != Phase::connecting) return false;
if (event.error != 0) close_once(Reason::connect_error);
else phase_ = Phase::open;
return true;
case Kind::enqueue:
if (phase_ != Phase::open || event.value > 32 - pending_) return false;
pending_ += static_cast<std::size_t>(event.value);
return true;
case Kind::sent:
if ((phase_ != Phase::open && phase_ != Phase::draining) || event.value > pending_)
return false;
pending_ -= static_cast<std::size_t>(event.value);
advance_close();
return true;
case Kind::peer_eof:
if (phase_ == Phase::connecting || phase_ == Phase::closed) return false;
read_eof_ = true;
advance_close();
return true;
case Kind::begin_drain:
if (phase_ == Phase::open) { phase_ = Phase::draining; deadline_ = event.value; }
else if (phase_ == Phase::draining || phase_ == Phase::write_closed)
deadline_ = std::min(deadline_, event.value); // A repeated request never extends it.
else return false;
advance_close();
return true;
case Kind::tick:
if ((phase_ == Phase::connecting || phase_ == Phase::draining ||
phase_ == Phase::write_closed) && event.value >= deadline_)
close_once(Reason::timeout);
return true;
case Kind::io_error:
close_once(Reason::io_error);
return true;
}
return false;
}
Snapshot snapshot() const noexcept { return {phase_, pending_, read_eof_}; }
Reason reason() const noexcept { return reason_; }
};
// One-slot registry models a stable index + generation handle. Single-thread owner.
// dispatch has no user callback and never exports a borrowed Connection pointer.
class Owner {
Actions& actions_;
std::optional<Connection> connection_;
std::uint64_t generation_;
bool retired_ = false;
Reason last_reason_ = Reason::none;
std::size_t last_discarded_ = 0;
bool matches(Handle handle) const noexcept {
return handle.slot == 0 && handle.generation == generation_ && connection_.has_value();
}
public:
explicit Owner(Actions& actions, std::uint64_t generation = 1) noexcept
: actions_(actions), generation_(generation) {}
std::optional<Handle> create(int modeled_fd, Tick connect_deadline) {
if (retired_ || connection_ || modeled_fd < 0) return std::nullopt;
connection_.emplace(actions_, modeled_fd, connect_deadline);
return Handle{0, generation_};
}
bool dispatch(Handle handle, Event event) {
if (!matches(handle)) return false;
const bool accepted = connection_->apply(event);
if (connection_->snapshot().phase == Phase::closed) {
last_reason_ = connection_->reason();
last_discarded_ = connection_->snapshot().pending;
connection_.reset(); // Reclaim only after apply returns.
if (generation_ == std::numeric_limits<std::uint64_t>::max()) retired_ = true;
else ++generation_;
}
return accepted;
}
std::optional<Snapshot> inspect(Handle handle) const noexcept {
if (!matches(handle)) return std::nullopt;
return connection_->snapshot();
}
Reason last_reason() const noexcept { return last_reason_; }
std::size_t last_discarded() const noexcept { return last_discarded_; }
};
void tests() {
Actions actions;
Owner owner(actions);
const auto old = *owner.create(42, 100);
assert(!owner.dispatch(old, {Kind::enqueue, 1})); // Connecting cannot accept application output.
assert(owner.dispatch(old, {Kind::connect_result})); // A checked SO_ERROR result of zero.
assert(!owner.dispatch(old, {Kind::enqueue, 33}));
assert(owner.dispatch(old, {Kind::enqueue, 8}));
assert(owner.dispatch(old, {Kind::peer_eof}));
assert(owner.inspect(old)->phase == Phase::open); // EOF does not close the send direction.
assert(owner.dispatch(old, {Kind::enqueue, 2})); // This protocol allows a final response.
assert(owner.dispatch(old, {Kind::begin_drain, 50}));
assert(!owner.dispatch(old, {Kind::enqueue, 1}));
assert(owner.dispatch(old, {Kind::sent, 4}));
assert(owner.inspect(old)->pending == 6 && actions.shutdowns == 0);
assert(!owner.dispatch(old, {Kind::sent, 7}));
assert(owner.dispatch(old, {Kind::sent, 6}));
assert(!owner.inspect(old) && owner.last_reason() == Reason::graceful);
assert(actions.closes == 1 && actions.shutdowns == 1);
assert(!owner.dispatch(old, {Kind::io_error}) && actions.closes == 1);
const auto fresh = *owner.create(42, 100); // Deterministically reuse the modeled fd number.
assert(fresh.generation != old.generation);
assert(!owner.dispatch(old, {Kind::enqueue, 8})); // Delayed event or worker result is rejected.
assert(!owner.dispatch({1, fresh.generation}, {Kind::io_error}));
assert(owner.dispatch(fresh, {Kind::connect_result}));
assert(owner.dispatch(fresh, {Kind::begin_drain, 50}));
assert(owner.inspect(fresh)->phase == Phase::write_closed && actions.shutdowns == 2);
assert(owner.dispatch(fresh, {Kind::begin_drain, 500}));
assert(actions.shutdowns == 2);
assert(owner.dispatch(fresh, {Kind::tick, 49}) && owner.inspect(fresh));
assert(owner.dispatch(fresh, {Kind::tick, 50}));
assert(owner.last_reason() == Reason::timeout && actions.closes == 2);
const auto rejected = *owner.create(42, 100);
assert(owner.dispatch(rejected, {Kind::connect_result, 0, ECONNREFUSED}));
assert(owner.last_reason() == Reason::connect_error && actions.closes == 3);
const auto connecting = *owner.create(42, 100);
assert(owner.dispatch(connecting, {Kind::tick, 100}));
assert(owner.last_reason() == Reason::timeout && actions.closes == 4);
const auto stalled = *owner.create(42, 100);
assert(owner.dispatch(stalled, {Kind::connect_result}));
assert(owner.dispatch(stalled, {Kind::enqueue, 10}));
assert(owner.dispatch(stalled, {Kind::sent, 3}));
assert(owner.dispatch(stalled, {Kind::begin_drain, 20}));
assert(owner.dispatch(stalled, {Kind::tick, 20}));
assert(owner.last_discarded() == 7 && actions.closes == 5 && actions.shutdowns == 2);
actions.fail_shutdown = true;
const auto failure = *owner.create(42, 100);
assert(owner.dispatch(failure, {Kind::connect_result}));
assert(owner.dispatch(failure, {Kind::begin_drain, 20}));
assert(owner.last_reason() == Reason::io_error && actions.closes == 6);
actions.fail_shutdown = false;
Owner exhausted(actions, std::numeric_limits<std::uint64_t>::max());
const auto last = *exhausted.create(42, 100);
assert(exhausted.dispatch(last, {Kind::io_error}));
assert(!exhausted.create(42, 100)); // Retire rather than wrap to an old generation.
assert(!exhausted.dispatch(last, {Kind::tick, 100}) && actions.closes == 7);
Actions reverse_actions;
Owner reverse(reverse_actions);
const auto local_first = *reverse.create(9, 100);
assert(reverse.dispatch(local_first, {Kind::connect_result}));
assert(reverse.dispatch(local_first, {Kind::begin_drain, 50}));
assert(reverse.inspect(local_first)->phase == Phase::write_closed);
assert(reverse.dispatch(local_first, {Kind::peer_eof}));
assert(reverse.last_reason() == Reason::graceful);
assert(reverse_actions.shutdowns == 1 && reverse_actions.closes == 1);
}
} // namespace model
class Fd {
int fd_;
public:
explicit Fd(int fd) : fd_(fd) {
if (fd < 0) throw std::system_error(errno, std::generic_category(), "socket");
}
Fd(const Fd&) = delete;
Fd& operator=(const Fd&) = delete;
~Fd() { if (fd_ >= 0) static_cast<void>(::close(std::exchange(fd_, -1))); }
int get() const noexcept { return fd_; }
};
void checked(int result, const char* operation) {
if (result < 0) throw std::system_error(errno, std::generic_category(), operation);
}
// Real Linux syscalls: one nonblocking TCP connection to this process's loopback listener.
// No application messages, generation reuse, graceful drain, or failure injection here.
void loopback_connect_test() {
Fd listener(::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
address.sin_port = 0;
checked(::bind(listener.get(), reinterpret_cast<const sockaddr*>(&address), sizeof(address)), "bind");
checked(::listen(listener.get(), 1), "listen");
socklen_t length = sizeof(address);
checked(::getsockname(listener.get(), reinterpret_cast<sockaddr*>(&address), &length), "getsockname");
Fd client(::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
const int result = ::connect(client.get(), reinterpret_cast<const sockaddr*>(&address), sizeof(address));
if (result < 0) {
if (errno != EINPROGRESS) throw std::system_error(errno, std::generic_category(), "connect");
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
bool completion_hint = false;
while (std::chrono::steady_clock::now() < deadline) {
const auto remaining = std::chrono::ceil<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
if (remaining.count() <= 0) break;
pollfd event{client.get(), POLLOUT, 0};
const int ready = ::poll(&event, 1, static_cast<int>(remaining.count()));
if (ready < 0) {
if (errno == EINTR) continue;
throw std::system_error(errno, std::generic_category(), "poll");
}
if (event.revents & POLLNVAL) throw std::runtime_error("invalid client fd");
if (ready > 0 && (event.revents & (POLLOUT | POLLERR | POLLHUP))) {
completion_hint = true;
break;
}
}
if (!completion_hint) throw std::runtime_error("loopback connect deadline expired");
}
int error = -1;
length = sizeof(error);
checked(::getsockopt(client.get(), SOL_SOCKET, SO_ERROR, &error, &length), "getsockopt SO_ERROR");
if (error != 0) throw std::system_error(error, std::generic_category(), "connect completion");
assert(length == sizeof(error));
}
int main() {
try {
model::tests();
loopback_connect_test();
std::cout << "lifecycle checks passed; stale handles rejected; generation retired; SO_ERROR=0\n";
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
g++ -std=c++20 -O2 -Wall -Wextra -Wpedantic -Werror examples/connection-lifecycle.cpp -o /tmp/connection-lifecycle
/tmp/connection-lifecycle
g++ -std=c++20 -O1 -g -Wall -Wextra -Wpedantic -Werror -fno-omit-frame-pointer -fsanitize=address,undefined -fno-pie -no-pie examples/connection-lifecycle.cpp -o /tmp/connection-lifecycle-san
/tmp/connection-lifecycle-san
本机 WSL、GCC 13.3.0 的正常构建和 ASan/UBSan 均通过,输出 lifecycle checks passed; stale handles rejected; generation retired; SO_ERROR=0。断言是验证的一部分,编译时不要定义 NDEBUG。
模型确定性覆盖连接未完成时拒绝输出、容量上限、部分发送、两个方向关闭的两种顺序、关闭后拒绝新输出、重复请求不延长期限、连接错误、建立超时、排空超时、半关闭动作失败、重复事件、旧代次以及代次耗尽。超时例在十个待发字节中已推进三个,记录剩余七个被丢弃;它只描述本地进度,没有判断远端业务结果。
真实部分绑定 127.0.0.1 的临时端口,创建非阻塞 client;connect 若进行中,则以 steady_clock 维护两秒 poll 预算。完成提示之后读取 SO_ERROR,非零值或系统调用失败都会退出报错。两秒是用户态等待预算,调度可能让返回更晚。测试没有调用 accept 后的业务处理、没有外部网络,也未用真实 fd 复用验证 generation。
实际 fd 由不可复制 RAII 对象独占,离开作用域关闭一次。Linux close 的错误不做盲目重试,以免误关后来复用的编号,依据见 close(2)。示例省略析构中的关闭错误日志;这项省略不改变应用应保存主要连接失败原因的要求。
高频追问
“已经取消工作任务,为什么还要检查 generation?”取消和完成可能交错,结果也可能已经排队。完成消息仍携带旧 Handle,owner 收到后必须验证。结果值应自行拥有数据;不要让工作线程在对象关闭后继续访问捕获的 Connection&。
“shared_ptr 能否替代 Handle?”它能延长内存寿命,却不保证对象仍处于允许输出的阶段,也不说明结果属于当前会话。即使拿到了强引用,仍要检查逻辑状态。长期保留强引用还可能延长缓冲占用,取消和资源预算需要另外规定。
“收到 HUP 就直接 close 可以吗?”HUP 可能与尚未读出的数据同时出现,不能跳过必要读取和 EOF/解析检查。连接策略也可能要求完成已有响应。应结合实际 I/O 结果、应用协议和关闭阶段决定动作,而不是只根据一个事件位丢弃全部状态。
“优雅关闭超时后,是不是应该无限等到 pending 归零?”截止的目的就是限制资源占用。到期后按协议和业务策略终止,记录尚未提交的字节及未确认请求。若业务不允许简单丢弃,应在上层保存可恢复状态,而不是让网络连接永久阻塞退出。
容易答错的点
- 可写只触发连接完成检查,SO_ERROR 才给出对应结果;读取选项成功不等于连接成功。
- 读 EOF 与写方向可用性分开;应用允许最后响应是协议选择,不是所有服务必须采用的策略。
- pending 为零描述本地输出进度,不提供对端业务完成保证。
epoll_ctl(DEL)不清除已经返回的用户态事件,派发仍需验证对象身份。- 代次比较要发生在取得安全对象访问之前,不能先解引用已失效指针。
- 大位宽只使代次耗尽更少见,不能把有限计数写成永不回绕。
性能分析
本例模型只有一个槽,身份查询和单次状态转换是有界常数工作;实际连接表、计时器和输出缓冲的成本取决于数据结构。把大量连接都集中在同一个 owner 可能降低同步复杂度,也可能让慢回调推迟所有连接的关闭检查,需要限制每轮工作量。
观测应包括各阶段连接数量、pending 字节、建立失败和关闭原因、超时后丢弃量、陈旧事件拒绝次数,以及截止到实际清理的延迟。报告建立和关闭延迟的分位数,控制连接尝试速率、对端读取速度、网络环境及事件循环负载。仅测一条空闲 loopback 连接,无法推导繁忙服务的关闭尾延迟。
连接失败时的重连也消耗 fd、内存和事件处理预算。设置并发尝试上限、重连退避和全局待发上限,测量失败风暴下是否仍能及时处理已有连接。该示例没有性能计时数据,真实 loopback 只作功能核查。
Quant/Low-Latency 场景
交易会话断开时,网络层应报告建立失败、I/O 错误、正常方向关闭或关闭超时,并保留发送进度和会话身份。业务层再区分哪些请求未发送、哪些已确认,以及哪些结果未知。不能把 timeout 直接映射成“订单未成交”,也不能无条件重发所有已提交请求。
来自风控、持久化或路由工作线程的迟到结果可能属于上一条会话。结果携带请求身份、会话代次和拥有数据,投递回 owner 后校验;重连后的新 fd 不能自动继承旧任务的输出权限。取消只限制后续工作,不能抹去已经到达对端的请求。
进程退出时先停止接受新业务,再推动各连接排空,并用共同停机预算约束全部等待。到期后记录未确认业务并关闭资源,持久化或恢复机制接管剩余责任。等待网络“看起来安静”不能代替明确的停机状态和业务确认。
相关专题
- epoll:LT vs ET:理解 readiness、事件缓存和单轮处理预算。
- TCP framing:把接收 EOF 与解析器截断状态联系起来。
- RAII 与异常安全:管理 fd 和错误路径中的唯一拥有者。
- 对象生命周期与布局:区分对象仍存活、借用有效和存储已回收。
分层面试题
L1 说明连接状态和各层完成条件;L2 跟踪同一事件批次中的身份、借用与回收;L3 处理重连、迟到任务和未知业务结果。设计评审应同时写出成功路径、截止触发者及资源最终由谁释放,避免让“关闭连接”承担未定义的多层含义。