I am trying to implement non-blocking for socket recv
and the problem is that I got an error -1 when there in no data but I expect to get EAGAIN
error.
You need to check errno
, not the length value to get the reason why the socket failed to return data. Also, EWOULDBLOCK
is the other error code you should check for in addition to EAGAIN
. Change your while loop as follows:
while(1)
{
int err;
printf("1\n");
length = recv(s, buffer, ETH_FRAME_LEN_MY, 0);
err = errno; // save off errno, because because the printf statement might reset it
printf("2\n");
if (length < 0)
{
if ((err == EAGAIN) || (err == EWOULDBLOCK))
{
printf("non-blocking operation returned EAGAIN or EWOULDBLOCK\n");
}
else
{
printf("recv returned unrecoverable error(errno=%d)\n", err);
break;
}
}
//printf ("buffer %s\n", buffer);
print(buffer, length);
}
Of course this infinite loop will get into a CPU wasting busy cycle while it's waiting for data. There are a variety of ways to be notified of data arriving on a socket without having to call recv()
in a spin loop. This includes select
and poll
calls.
I got an error -1 when there in no data but I expect to get EAGAIN error.
-1 tells you there is an error. errno
tells you what the error was.