【发布时间】:2021-05-15 02:04:50
【问题描述】:
我无法理解 select 系统调用的使用。根据select documentation,select 将在超时或套接字准备好进行 I/O 操作后返回。 socket is ready for I/O operation 是什么意思?
received_len = 0
do {
/* There is only one fd in readfds */
rv = select(fd+1, &readfds, NULL, NULL, timeout)
if (rv < 0){
/*socket select failed.*/
break
}else if (rv == 0){
/*socket timeout.*/
break
}else
/* Go for reading */
readbytes = read(fd, (buf + received_len), (expected_len - received_len))
if (readbytes < 0)
{
/*read fail*/
break
}
received_len += readbytes;
}while(received_len < expected_len)
虽然当对等套接字连接关闭时,选择会超时。但是在关闭对等连接后,选择返回 1 并且读取发生在套接字上。然后 read 调用返回 0 (这基本上意味着对等端终止)。我认为 select 会超时,因为套接字还没有准备好进行读取操作,但这并没有发生。
【问题讨论】:
-
请参阅this answer 来回答您的问题。 0 是读取的有效结果(表示 EOF)。 select 不承诺您将在阅读时获得一些字节;只是 next 读取操作不会被阻塞,不管是什么原因。
-
在您给出的示例中,您将读取失败视为有效案例;为什么EOF案例会如此不同? (我只想写
if (readbytes <= 0)以便在这两种情况下都中断)。