首页 > 解决方案 > 在 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()

如果我没有发现这些错误,我的服务器会在客户端关闭连接时停止工作。

如何捕获这些错误并返回接受以与另一个客户端建立连接?

标签: csocketstcperror-handling

解决方案


错误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. */
  }

推荐阅读