I was going through a serial program and I observed that they use select() before using read(). Why exactly is this required. Why cant we just directly call read() and check if it fails or not ? Also why do we have to increment the file descriptor by 1 and pass it while I am passing the file descriptor set already to select()?
Example:
r=select(fd+1, &fds, NULL, NULL, &timeout);
where fds already has the value of fd
The
select()system call tells you whether there is any data to read on the file descriptors that you’re interested in. Strictly, it is a question of whether a read operation on the file descriptor will block or not.If you execute
read()on a file descriptor — such as that connected to a serial port — and there is no data to read, then the call will hang until there is some data to read. Programs usingselect()do not wish to be blocked like that.You also ask:
That’s probably specifying the size of the FD_SET. The first argument to
select()is known asnfdsand POSIX says:So, to test a file descriptor
n, the value innfdsmust be at leastn+1.