recv with non-blocking socket

一世执手 提交于 2019-12-03 21:23:45
selbie

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!