select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become “ready” for some class of I/O operation (e.g., input possible).
The timeout argument specifies the interval that select() should block waiting for a file descriptor to become ready. The call will block until either:
a file descriptor becomes ready;
the call is interrupted by a signal handler; or
the timeout expires.
Example
#include<stdio.h>#include<stdlib.h>#include<sys/time.h>#include<sys/types.h>#include<unistd.h>intmain(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()”);elseif (retval)printf(“Data is available now.\n”); /* FD_ISSET(0, &rfds) will be true. */elseprintf(“No data within five seconds.\n”);exit(EXIT_SUCCESS);}
Allocate bit maps, all fds from 3 registered fd sets have a bit presented.
/* * We need 6 bitmaps (in/out/ex for both incoming and outgoing), * since we used fdset we need to allocate memory in units of * long-words. */ size =FDS_BYTES(n); bits = stack_fds;if (size >sizeof(stack_fds) /6) { /* Not enough space in on-stack array; must use kmalloc */ ret =-ENOMEM; bits =kmalloc(6* size, GFP_KERNEL);if (!bits)goto out_nofds; } fds.in = bits; fds.out = bits + size; fds.ex = bits +2*size; fds.res_in = bits +3*size; fds.res_out = bits +4*size; fds.res_ex = bits +5*size;if ((ret =get_fd_set(n, inp, fds.in)) || (ret =get_fd_set(n, outp, fds.out)) || (ret =get_fd_set(n, exp, fds.ex)))goto out;zero_fd_set(n, fds.res_in);zero_fd_set(n, fds.res_out);zero_fd_set(n, fds.res_ex); ret =do_select(n,&fds, end_time);
Loop and fetch each file, check its state, mark the bit if qualified. int do_select(int n, fd_set_bits *fds, struct timespec *end_time)