How to catch a “connection reset by peer” error in C socket?

妖精的绣舞 提交于 2019-12-04 19:28:21

Just examine errno when read() returns a negative result.

There is normally no crash involved.

while (...) {
    ssize_t amt = read(sock, buf, size);
    if (amt > 0) {
        // success
    } else if (amt == 0) {
        // remote shutdown (EOF)
    } else {
        // error

        // Interrupted by signal, try again
        if (errno == EINTR)
            continue;

        // This is fatal... you have to close the socket and reconnect
        // handle errno == ECONNRESET here

        // If you use non-blocking sockets, you also have to handle
        // EWOULDBLOCK / EAGAIN here

        return;
    }
}

It isn't an exception or a signal. You can't catch it. Instead, you get an error which tells you that the connection has been resetted when trying to work on that socket.

int rc = recv(fd, ..., ..., ..., ...);

if (rc == -1)
{ 
  if (errno == ECONNRESET)
    /* handle it; there isn't much to do, though.*/
  else
     perror("Error while reading");
}

As I've written, there isn't much you can do. If you're using some I/O multiplexer, you may want to remove that file descriptor from further monitoring.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!