【发布时间】:2019-07-04 00:51:31
【问题描述】:
成功读取设置为非阻塞的套接字后,该套接字暂时不可用。第一次调用read 时已接收到所有数据,但错误返回值会持续约 5 秒。之后read 返回 0 并且套接字再次可用。
为什么套接字首先返回错误?
设置非阻塞套接字:
/* Non blocking */
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
读取套接字并打印:
result = read(sockfd, response + bytes_read, RESPONSE_SIZE - bytes_read);
printf("%d | %d | %s\n", (int)result, errno, strerror(errno));
printf("%d | %d | %d | %d | %d | %d | %d | %d \n",
EAGAIN, EWOULDBLOCK, EBADF, EFAULT, EINTR, EINVAL, EIO, EISDIR);
结果:
152 | 115 | Operation now in progress
11 | 11 | 9 | 14 | 4 | 22 | 5 | 21
-1 | 11 | Resource temporarily unavailable
11 | 11 | 9 | 14 | 4 | 22 | 5 | 21
【问题讨论】:
-
即使它是非阻塞的,无法获取数据也是一个错误,这就是为什么您在
errno中得到EWOULDBLOCK并返回-1。
标签: c file-descriptor