Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query on Select System Call

Tags:

c

sockets

select() is defined as :

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout);

nfds represents the highest file descriptor in all given sets plus one. I would like to know why is this data required for select() when the fd_set information is available.

If the FDs in the set are say, 4, 8, 9 ,the value of nfds would be 10. Would select() moniter fds 9,8,7,6,5,4 ?

like image 966
Prabhu. S Avatar asked Mar 13 '09 19:03

Prabhu. S


People also ask

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.

What are the three file descriptors used in the select () call?

On success, select() and pselect() return the number of file descriptors contained in the three returned descriptor sets (that is, the total number of bits that are set in readfds, writefds, exceptfds) which may be zero if the timeout expires before anything interesting happens.

What is fd_set in socket?

The fd_set structure is used by various Windows Sockets functions and service providers, such as the select function, to place sockets into a "set" for various purposes, such as testing a given socket for readability using the readfds parameter of the select function.


1 Answers

The catch is that fd_set is not really a "set" in the way you're thinking. The behind-the-scenes detail is that the implementation of an fd_set is just an integer that is used as a bitfield. In other words, executing

fd_set foo;
FD_CLEAR(&foo);
FD_SET(&foo, 3);

Sets foo to decimal value 8 - it sets the fourth-least-singificant bit to 1 (remember that 0 is a valid descriptor).

FD_SET(&foo, 3);

is equivalent to

foo |= (1 << 3);

So in order for select to work right, it needs to know which bits of the fd_set are bits that you care about. Otherwise there would be no way for it to tell a zero bit that is "in" the set but set to false from a zero bit that is "not in" the set.

In your example, a fd_set with 4, 8, and 9 set and n = 10 is interpreted as "A set with 10 entries (fds 0-9). Entries 4, 8, and 9 are true (monitor them). Entries 1,2,3,5,6,7 are false (don't monitor them). Any fd value greater than 9 is simply not in the set period."

like image 85
Tyler McHenry Avatar answered Sep 23 '22 04:09

Tyler McHenry