【问题标题】:Select returns success even if connection is terminated by peer socket即使连接被对等套接字终止,选择也会返回成功
【发布时间】: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 &lt;= 0) 以便在这两种情况下都中断)。

标签: c sockets unix


【解决方案1】:

来自您在问题中引用的documentation

读取文件

监视此集合中的文件描述符以查看是否 他们已经准备好阅读了。文件描述符已准备就绪 如果读取操作不会阻塞,则用于读取;在 特别是,文件描述符在结束时也准备好了 - 文件。

【讨论】:

    猜你喜欢
    • 2016-04-10
    • 2015-08-09
    • 2016-08-23
    • 1970-01-01
    • 2015-04-12
    • 2016-04-30
    • 2011-12-30
    • 2020-11-12
    • 2011-06-02
    相关资源
    最近更新 更多