BSD Sockets Interface Programmer's Guide

Chapter 3 73
Advanced Topics for Stream Sockets
Synchronous I/O Multiplexing with Select
The following example illustrates the select system call. Since it is
possible for a process to have more than 32 open file descriptors, the bit
masks used by select are interpreted as arrays of integers. The header
file sys/types.h contains some useful macros to be used with the
select() system call, some of which are reproduced below.
/*
* These macros are used with select(). select() uses bit masks of
* file descriptors in long integers. These macros manipulate such
* bit fields (the file system macros use chars). FD_SETSIZE may
* be defined by the user, but must be = u.u_highestfd + 1. Since
* the absolute limit on the number of per process open files is
* 2048, FD_SETSIZE must be large enough to accommodate this many
* file descriptors.
* Unless the user has this many files opened, FD_SETSIZE should
* be redefined to a smaller number.
*/
typedef long fd_mask
#define NFDBITS (sizeof (fd_mask) * 8 /* 8 bits per byte
#define howmany (x,y) (((x)+((y)-1))/(y))
typedef struct fd_set {
fd_mask fds_bits [howmany (FD_SETSIZE, NFDBITS)]; */
} fd_set;
#define FD_SET(n,p) ((p)->fds_bits[(n)/NFDBITS]
#|= (1 << ((n) % NFDBITS)))
#define FD_CLR(n,p) ((p)->fds_bits[(n)/NFDBITS]
#&= ˜(1 << ((n) % NFDBITS)))
#define FD_ISSET(n,p) ((p) ->fds_bits[(n)/NFDBITS]
#& (1 << ((n) % NFDBITS)))
#define FD_ZERO(p) memset((char *) (p), (char) 0, sizeof (*(p)))
do_select(s)
int s; /* socket to select on, initialized */
{
struct fd_set read_mask, write_mask; /* bit masks */
int nfds; /* number to select on */
int nfd; /* number found */
for (;;) { /* for example... */
FD_ZERO(&read_mask); /* select will overwrite on return */
FD_ZERO(&write_mask);
FD_SET(s, &read_mask); /* we care only about the socket */
FD_SET(s, &write_mask);
nfds = s+1; /* select descriptors 0 through s */
nfd = select(nfds, &read_mask, &write_mask, (int *) 0,
(struct timeval *) 0);/* will block */
if (nfd == -1) {
perror( “select: unexpected condition” );