Roman Rdgz
Roman Rdgz

Reputation: 13274

Reading sockets gives errno EAGAIN when there is no data to read, but also if I disconnect network

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)

Upvotes: 1

Views: 2661

Answers (1)

stefaanv
stefaanv

Reputation: 14392

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)

Upvotes: 3

Related Questions