5,530
社区成员




//处理32 个以上的打开文件。howmany 、fd_set 和NFDBITS 都在<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.*/
for (k=0; k < NWORDS; k++)
readmask.fds_bits[k] = 0;
for (i=0, k=0; i < NTTYS && k < NWORDS; k++)
for (j=0; j < NFDBITS && i < NTTYS; j++, i++) {
ttymask[i] = MASK(tty[i]);
readmask.fds_bits[k] |= ttymask[i];
}
timeout.tv_sec = 5;
timeout.tv_usec = 0;
for (k=0; k < NWORDS; k++)
readfds.fds_bits[k] = readmask.fds_bits[k];
/* 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, k=0; i < NTTYS && k < NWORDS; k++)
for (j=0; j < NFDBITS && i < NTTYS; j++, i++)
if (ttymask[i] & readfds.fds_bits[k])
/* Read from tty[i]. The code for reading
* is not shown here.
*/
else printf ("tty[%d] is not ready for reading \n",i);
......