LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C Network programming, select() (https://www.linuxquestions.org/questions/programming-9/c-network-programming-select-946424/)

alaios 05-23-2012 02:39 AM

C Network programming, select()
 
Dear all,
I have a somehow trivial question about network programming in c.

I was reading yesterday the man pages of select()
Code:

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

and as you can see the first argument is an integer.
According to the man page
Code:

nfds is the highest-numbered file descriptor in any of the three sets, plus 1.

I am trying to understand two things
1) Why the highest number there is needed? Before using select one has few file descriptors (actually) that want to track. Would not make sense to pass directly those instead of the maximum number. What one probably wants to do is to ask from kernel "Please look my file descriptors X,Y,Z". How kernel handles that when it know the maximum number of those?

2) Why +1 is needed? Would not be more convenient just to give the max number and for the reason (which I do not also understand) the function then to add +1 to the provided number?

I would like to than k you in advance for your help
B.R
Alex

NevemTeve 05-23-2012 03:51 AM

The file-descriptors are stored in the three bit-vectors (readfds, writefds, exceptfds), the first parameter only informs the kernel how long it has to check to bit-vector.
For example, if you only want to check the standard input (handle==0), then set nfds to 1.

jhwilliams 05-23-2012 10:44 AM

As far as I could tell from looking it up, it's a legacy feature that short-circuits some work.

I guess having select() implemen a MAX(int *fds) on the inputs is too much work?

Sure, maybe it does save a bit of work.

But I think the signature could be reworked into something a little more sensible.

dwhitney67 05-23-2012 10:53 AM

Quote:

Originally Posted by jhwilliams (Post 4685671)
But I think the signature could be reworked into something a little more sensible.

I think someone came to the same conclusion long ago, and developed poll(), and then later epoll().

I'm an old-school developer, so I still use select(); it just add a simple line of code to determine the max file descriptor. Something like:
Code:

int maxfd = -1;
...
maxfd = (fd > maxfd ? fd : maxfd);
...
select(maxfd + 1, &readfds, 0, 0, 0);


jhwilliams 05-23-2012 06:44 PM

Quote:

Originally Posted by dwhitney67 (Post 4685682)
I think someone came to the same conclusion long ago, and developed poll(), and then later epoll()

Lol.


All times are GMT -5. The time now is 05:34 PM.