简体   繁体   中英

Using non-blocking socket. errno is always EAGAIN after calling recvfrom

I'm porting my networking code from Windows to Linux, but not without problems. For some reason, recvfrom wont work properly when I'm setting the socket to be non-blocking. You see, errno is always EAGAIN after I call recvfrom and it doesn't matter how many packets I receive, it's always EAGAIN. The code is running fine if I comment out the code that's setting the socket to be no-blocking. Well then it's working, but it's blocking...

Here's the code I'm using to set the socket to non-blocking:

int nonBlocking = 1;
if ( fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking ) == -1 )
{
    std::cout << "failed to set non-blocking socket" << std::endl;
    return false;
}

Any ideas about what I'm doing wrong? (It's working fine in my Windows build using:

DWORD nonBlocking = 1;
ioctlsocket( handle, FIONBIO, &nonBlocking );

First, before check the errno value, you should check the return value of recvfrom() .

If it returns -1 then errno value will make sense.

From recvfrom manpage:

If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket is nonblocking (see fcntl(2)), in which case the value -1 is returned and the external variable errno set to EAGAIN.

In a nutshell:

at the moment you call recvfrom , there's nothing to read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM