The socket call gets read, write, and exception status on a group of sockets.
The BSD version monitors the activity on sockets by specifying an array (fd_set) of socket numbers for which the caller wants to read the data, write the data, and check exception-pending conditions. The BSD version provides FD_SET, FD_CLR, FD_ISSET, and FD_ZERO macros to add or delete socket numbers from the array.
Syntax
#include <types.h> #include <unistd.h> #include <sys\time.h> int select(nfds, readfds, writefds, exceptfds, timeout) int nfds; fd_set *readfds; fd_set *writefds; fd_set *exceptfds; struct timeval *timeout;
Parameters
nfds
Description
This call monitors activity on a set of different sockets until a timeout expires, to see if any sockets are ready for reading or writing, or if any exception-pending conditions are pending.
Reinitializing readfds, writefds, and exceptfds every time select() is called is required.
If timeout is a NULL pointer, the call blocks indefinitely until one of the requested conditions is satisfied. If timeout is non-NULL, it specifies the maximum time to wait for the call to complete. To poll a set of sockets, the timeout pointer should point to a zeroed timeval structure. The timeval structure is defined in the <SYS\TIME.H> header file and contains the following fields:
struct timeval { long tv_sec; /* Number of seconds */ long tv_usec; /* Number of microseconds */ }
An fd_set is made up of an array of integers. Macros are provided to manipulate the array.
Macro
Note: For macros FD_SET, FD_CLR, FD_ISSET, and FD_ZERO, define the parameters socket and array_address in the following manner:
int socket;struct fd_set *array_address;
Setting any of the descriptor pointers to zero indicates that no checks are to be made for the conditions. For example, setting exceptfds to be a NULL pointer causes the select call to check for only read and write conditions.
Return Values
The total number of ready sockets (in all arrays) is returned. The value -1 indicates an error. The value 0 indicates an expired time limit. If the return value is greater than 0, the socket descriptors in each array that are not ready are removed from the array and fd_array is rearranged so that the ready sockets are at the top. The fd_count parameter is adjusted accordingly and returned. You can get the specific error code by calling sock_errno() or psock_errno().
sock_errno() Value
Examples
Following is an example of the select() call.
...fd_set readsocks; fd_set writesocks; fd_set exceptsocks; struct timeval timeout; int number_found; ... /* add socket to read/write/except arrays. To add descriptor s use * FD_SET (s, &readsocks); * */ ... number_found = select(0,&readsocks, &writesocks, &exceptsocks, &timeout);
Related Calls