在C语言中处理send e recv错误

在C语言中处理send e recv错误,c,sockets,tcp,error-handling,C,Sockets,Tcp,Error Handling,我是C语言新手,正在编写TCP服务器 // create a socket, bind and listen while(1) { accept: int conn_sock = accept(...); // here some recv and send calls } 如果发生ECONNRESET或EINTR,我希望防止服务器关闭。如果在发送或接收数据时出现此错误之一,我希望转到接受(如果accept()也因某种原因失败,则希望转到acceptlabel) 如果我没有捕捉到这些错误

我是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
label)

如果我没有捕捉到这些错误,如果客户端关闭连接,我的服务器将停止工作

如何捕获这些错误并返回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. */
  }

我看这里没有问题。您的要求非常明确,为什么不简单地编写实现它们的代码呢?我认为问题很清楚:如何捕获这些错误并返回接受?谢谢,对于发送和接收功能,我可以这样做吗?@GJCode:我可以,但您也可以…;):唯一的区别是
send()
recv()
返回一个
ssize\u t
而不是
int
,并且
errno
的值不同。