1
votes

I am calling read function to catch received packets if available. When there is no packet to get, i'm getting errno EAGAIN, but when network is disconnected I am also getting EAGAIN, so I am not able to difference both scenarios.

    while ( ((n = read(sockfd, &(buffer[pos]), 1)) > 0) and not messageFound) {

            //reading byte by byte
            if (n == 1) {
               // Some stuff.. 
            }
        }

// Never returning 0, but when returning negative values:
        if (n < 0){
            qDebug()<< "Read error #" << errno << ": " << strerror(errno);
            if(errno != EAGAIN){ // It is always this error, so it's never entering here
                qDebug()<< "Disconnected. Reason #" << errno << ": " << strerror(errno);
                *connected = false;
            }
        }

Is there any way of checking if socket has been disconnected, or know if there is some packet available before calling read? (I tried with select but doesn't seem to work)

1
Note that errno after calling qDebug() may or may not be what you'd expect.Alexis Wilke

1 Answers

3
votes

For POSIX sockets, the difference between closed connection and no data ready is in the return value. When a connection is closed, the return value is 0, when there is no data it has a negative value (see man page)