Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is select used in Linux

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

like image 217
user1667307 Avatar asked Jan 27 '13 05:01

user1667307


People also ask

What does select do in Linux?

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).

What is select system?

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.

What does select () do in C?

The select() function indicates which of the specified file descriptors is ready for reading, ready for writing, or has an error condition pending.

Why Epoll is faster than select?

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.


1 Answers

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 first nfds descriptors shall be checked in each set; that is, the descriptors from zero through nfds-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.

like image 85
Jonathan Leffler Avatar answered Oct 05 '22 06:10

Jonathan Leffler