检测套接字连接何时断开 C / C++ Unix

Detect when Socket Connection is disconnected C / C++ Unix

我知道这个问题已经讨论过好几次了,但我没能在 Unix 上用 C/C++ 检测套接字是否断开连接。 有什么办法吗?

谢谢,来自布鲁克斯的问候

我假设套接字可能被对方关闭了。

这在很大程度上取决于您要检测断开连接的位置。

如果您处于阻塞状态recvmanpage

These calls return the number of bytes received, or -1 if an error occurred. In the event of an error, errno is set to indicate the error.

When a stream socket peer has performed an orderly shutdown, the return value will be 0 (the traditional "end-of-file" return).

如果您想在 send 上了解: manpage

On success, these calls return the number of bytes sent. On error, -1 is returned, and errno is set appropriately.