recv with non-blocking socket

后端 未结 2 1499
心在旅途
心在旅途 2021-02-10 00:12

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.

相关标签:
2条回答
  • 2021-02-10 00:31

    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.

    0 讨论(0)
  • 2021-02-10 00:40

    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.

    0 讨论(0)
提交回复
热议问题