-1

I am having trouble understanding the use of select system call. As per select documentation , select will return after timeout or socket is ready for I/O operation. What does it mean by 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)

I though select will timed out when peer socket connection closes. but after closing peer connection select returns 1 and read happens on socket. Then read call returns 0 (Which basically means peer terminated). I thought select will be timed out since the socket is not still ready for read operation but that is not happenning.

Cracken
  • 306
  • 2
  • 5
  • 17
  • 4
    See [this answer](https://stackoverflow.com/a/66135105/11527076) to your question. 0 is a valid result for read (meaning EOF). select does not make the promise that you will obtain some bytes when reading; just that the **next** read operation won't be blocked, whatever the reason. – prog-fh Feb 11 '21 at 10:43
  • 1
    In the example you gave, you consider the read failure as a valid case; why the EOF case would be so different? (I would just write `if (readbytes <= 0)` in order to break in both cases). – prog-fh Feb 11 '21 at 10:50

1 Answers1

2

From the documentation you cited in the question

readfds

The file descriptors in this set are watched to see if they are ready for reading. A file descriptor is ready for reading if a read operation will not block; in particular, a file descriptor is also ready on end-of- file.

prog-fh
  • 13,492
  • 1
  • 15
  • 30