Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i know about select() :

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


nfds is argument specifies the number of descriptors to be tested.
if i set nfds to be 0. This way will impact the select()?
for example:

XML
#include <stdio.h>
       #include <stdlib.h>
       #include <sys/time.h>
       #include <sys/types.h>
       #include <unistd.h>
       int
       main(void)
       {
           fd_set rfds;
           struct timeval tv;
           int retval;
           /* Watch stdin (fd 0) to see when it has input. */
           FD_ZERO(&rfds);
           FD_SET(0, &rfds);
           /* Wait up to five seconds. */
           tv.tv_sec = 5;
           tv.tv_usec = 0;
           retval = select(1, &rfds, NULL, NULL, &tv);
           /* Don't rely on the value of tv now! */
           if (retval == -1)
               perror("select()");
           else if (retval)
               printf("Data is available now.\n");
               /* FD_ISSET(0, &rfds) will be true. */
           else
               printf("No data within five seconds.\n");
           exit(EXIT_SUCCESS);
       }



if i set nfds to be 1, it will be ok and printf " Data is available now. ".
But if i set it to be 0, it still can run but it take more time and printf "No data within five seconds".


please tell me why or tell me where i can find the answer, thank you!
Posted

1 solution

nfds is the number of file descriptors that you are listening for in select(), but that description is a little misleading.

File descriptors start at 0 and go up from there. Thus, the fd_sets can be bit arrays, where if you want to listen to the nth file descriptor then you set the n+1th bit in the fd_set. However, select() needs to know where to stop, so that's where nfds comes in, and that's why nfds must be set to the maximum file descriptor number that you want to listen to plus one.

When you set it to 0, select() is effectively listening to no file descriptors, which is why it hits the timeout.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900