select.2 (2010 09)

s
select(2) select(2)
EXAMPLES
The following call to select() checks if any of 4 terminals are ready for reading.
select() times
out after 5 seconds if no terminals are ready for reading. Note that the code for opening the terminals or
reading from the terminals is not shown in this example. Also, note that this example must be modified if
the calling process has more than 32 file descriptors open. Following this first example is an example of
select with more than 32 file descriptors.
#define MASK(f) (1 << (f))
#define NTTYS 4
int tty[NTTYS];
int ttymask[NTTYS];
int readmask = 0;
int readfds;
int nfound, i;
struct timeval timeout;
/* First open each terminal for reading and put the
* file descriptors into array tty[NTTYS]. The code
* for opening the terminals is not shown here.
*/
for (i=0; i < NTTYS; i++) {
ttymask[i] = MASK(tty[i]);
readmask |= ttymask[i];
}
timeout.tv_sec = 5;
timeout.tv_usec = 0;
readfds = readmask;
/* select on NTTYS+3 file descriptors if stdin, stdout
* and stderr are also open
*/
if ((nfound = select (NTTYS+3, &readfds, 0, 0, &timeout)) == -1)
perror ("select failed");
else if (nfound == 0)
printf ("select timed out \n");
else for (i=0; i < NTTYS; i++)
if (ttymask[i] & readfds)
/* Read from tty[i]. The code for reading
* is not shown here.
*/
else printf ("tty[%d] is not ready for reading \n",i);
The following example is the same as the previous example, except that it works for more than 32 open
files. Definitions for howmany, fd_set, and NFDBITS are in <sys/types.h>.
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#define MASK(f) (1 << (f))
#define NTTYS NOFILE - 3
#define NWORDS howmany(FD_SETSIZE, NFDBITS)
int tty[NTTYS];
int ttymask[NTTYS];
struct fd_set readmask, readfds;
int nfound, i, j, k;
struct timeval timeout;
/* First open each terminal for reading and put the
* file descriptors into array tty[NTTYS]. The code
* for opening the terminals is not shown here.
*/
4 Hewlett-Packard Company 4 HP-UX 11i Version 3: September 2010