recv函数返回值处理(包括errno的处理)

1、recv()函数的返回值:

>0:接收到的数据大小;

=0:连接关闭;

<0:出错。

 在出错的情况下,

这三种错误下认为连接是正常的,继续接收

if(errno == EINTR ||(errno == EAGAIN)||errno == EWOULDBLOCK)
                    continue;

if(FD_ISSET(connfd,&r_set)
{
        int irecv,iunrecv;
        iunrecv = length;
        while(iunrecv>0)
        {
            irecv = recv(concfd,buff,iunrecv,0)
            if(irecv==0)
            {
                 printf("recv error:%s",strerror(errno));
                 return -1;
            }
            if(irecv<0)            
            {//这条判断是针对非阻塞的情况下,会发生的错误//当阻塞的情况下,recv函数会直接阻塞在调用的地方,不会执行到这里。
                if(errno == EINTR ||(errno == EAGAIN)||errno == EWOULDBLOCK)
                    continue;

                //阻塞和非阻塞都会产生
                 printf("recv error:%s",strerror(errno));
                 return -1;
            }
            iunrecv -= irecv;
            buff += irecv;
        }
    }

注意:

recv的返回值为0时,表示连接关闭,并不是说没有读到数据,

因为,对于阻塞的套接字,没有读到数据,函数不会返回,会阻塞等待。

对于非阻塞的套接字,没有读到数据,函数会返回-1,错误号时 EAGAIN。