Search code examples
csocketsepipe

How to fix EPIPE after reconnecting to Server


I have a C socket client program where one thread is for receiving data and another for sending. If the server shuts down then the sender gets EPIPE. If I reconnect the same socket then it can receive data but the sender still gets EPIPE.

How to fix this?

Update: Actually sender seems to send data as I see number of byte sent. But errno is still set to broken pipe. Before I only checked errno. Shouldn't it be changed to successful?


Solution

  • If I reconnect the same socket then it can receive data but the sender still gets EPIPE.

    That can only mean that the sender is still sending via the old socket; also that you haven't closed the old socket.

    sender seems to send data as I see number of byte sent. But errno is still set to broken pipe. Before I only checked errno. Shouldn't it be changed to successful?

    No. It is only valid to check errno when an immediately prior system call has returned -1. Example:

    int rc = send(...);
    if (rc < 0)
    {
        if (errno == EWOULDBLOCK) // or EAGAIN *and* we are in non-blocking mode
        {
            // queue the write and return to the select() loop
        }
        else
        {
            perror("send"); // for example
        }
    }
    else
    {
        // write succeeded ...
    }