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
select() allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible).
select is a system call and application programming interface (API) in Unix-like and POSIX-compliant operating systems for examining the status of file descriptors of open input/output channels. The select system call is similar to the poll facility introduced in UNIX System V and later operating systems.
The select() function indicates which of the specified file descriptors is ready for reading, ready for writing, or has an error condition pending.
The main difference between epoll and select is that in select() the list of file descriptors to wait on only exists for the duration of a single select() call, and the calling task only stays on the sockets' wait queues for the duration of a single call.
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 using select()
do not wish to be blocked like that.
You also ask:
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
?
That's probably specifying the size of the FD_SET. The first argument to select()
is known as nfds
and POSIX says:
The
nfds
argument specifies the range of descriptors to be tested. The firstnfds
descriptors shall be checked in each set; that is, the descriptors from zero throughnfds-1
in the descriptor sets shall be examined.
So, to test a file descriptor n
, the value in nfds
must be at least n+1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With