c - 在 C 中处理 send e recv 错误
问题描述
我是 C 语言的新手,我正在编写一个 TCP 服务器
// create a socket, bind and listen
while(1) {
accept:
int conn_sock = accept(...);
// here some recv and send calls
}
ECONNRESET
如果发生或EINTR
发生,我想防止服务器关闭。如果在发送或接收数据时发生其中一个错误,我想去接受(如果由于某种原因也失败了,也想去accept
标签)。accept()
如果我没有发现这些错误,我的服务器会在客户端关闭连接时停止工作。
如何捕获这些错误并返回接受以与另一个客户端建立连接?
解决方案
错误accept()
返回-1
。然后可以从中读取错误的原因errno
。
一种可能的方法是:
int errno_accept;
while (1)
{
errno_accept = 0;
int accepted_socket = accept(...);
if (-1 == accepted_socket)
{
errno_accept = errno;
switch(errno_accept)
{
case EINTR:
case ECONNRESET: /* POSIX does *not* define this value to be set
by a failed call to accept(), so this case is useless. */
default:
/* Catch unhandled values for errno here. */
break; /* Treat them as fatal. */
...
} /* while (1) */
if (0 != errno_accept)
{
/* Handle fatal error(s) here. */
}
推荐阅读
- python - 如何在 tkinter python 中禁用复选框的动画
- arrays - 对文档中的值求和
- orbeon - 如何将导航与使用表单生成器创建的 orbeon 表单一起使用?
- linux - top 通过命令行选项添加过滤器命令
- android - Room - 在运行时(在用户端)添加或删除列?
- java - JSON对象数组到Java POJO
- java - 如何在 antlr4 访问者方法中抛出异常?
- spring - spring findAll by parent 属性
- python - 我可以更改函数参数的默认值吗?
- google-apps-script - 谷歌脚本,onEdit 功能突然不起作用,如何解决?