Linux:close()返回“坏文件描述符”后的recv

时间:2014-02-24 17:55:45

标签: linux sockets tcp

我认为关闭TCP连接(在文件描述符上调用close())会使其处于停止发送数据的状态,但在对等体也关闭其套接字之前仍然可以接收数据。但是,在测试时,我在recv()调用上得到“Bad File Descriptor”。我希望recv()返回code = 0。请注意,select()调用成功。

if (0 != close(sockfd))
{
    err_sys("close failed");
}

printf("select waiting for response\n");
FD_ZERO(&rset);
FD_SET(sockfd, &rset);
wset = rset;

printf("select waiting for response\n");
if ((stat = select(sockfd + 1, &rset, NULL, NULL, NULL)) == 0)
{
    errno = ETIMEDOUT;
    err_sys("connect timed out");
}
printf("got response\n");

stat = recv(sockfd, buff, sizeof(buff), 0);
if (0 == stat) {
    printf("remote closed\n");
}
else if (-1 == stat) {
    if (errno == EWOULDBLOCK || errno == EAGAIN) {
        err_sys("would block again\n");
    } else {
        err_sys("recv failed");
    }
} else {
    err_sys("unexpected return code");
}

1 个答案:

答案 0 :(得分:4)

您希望shutdown(fd, SHUT_WR)仅关闭写入但仍能读取。 close(fd)将使文件描述符无效,就像您关闭了本地文件的开放路径一样。

http://man7.org/linux/man-pages/man2/shutdown.2.html