#include <sys/select.h>
/* According to earlier standards */
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
void FD_CLR(int fd, fd_set *set);
int FD_ISSET(int fd, fd_set *set);
void FD_SET(int fd, fd_set *set);
void FD_ZERO(fd_set *set);
int pselect(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, const struct timespec *timeout,
const sigset_t *sigmask);
DESCRIPTION
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). A file descriptor is considered ready if it is possible to perform the corresponding I/O
operation (e.g., read(2)) without blocking.
The operation of select() and pselect() is identical, with three differences:
(i)select() uses a timeout that is a struct timeval (with seconds and microseconds), while pselect() uses a struct timespec (with seconds and
nanoseconds).
(ii)select() may update the timeout argument to indicate how much time was left. pselect() does not change this argument.
(iii)select() has no sigmask argument, and behaves as pselect() called with NULL sigmask.
The timeout
The time structures involved are defined in <sys/time.h> and look like
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
and
struct timespec {
long tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
select()机制中提供一fd_set的数据结构,实际上是一long类型的数组,每一个数组元素都能与一打开的文件句柄
(不管是socket句柄,还是其他文件或命名管道或设备句柄)建立联系,建立联系的工作由程序员完成,当调用select()时,
由内核根据IO状态修改fd_set的内容,由此来通知执行了select()的进程哪一socket或文件发生了可读或可写事件。
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main(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()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");
exit(EXIT_SUCCESS);
}
#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>
int main(int argc, char **argv){
fd_set fdset;
FD_ZERO (&fdset); /*清空集合中所有的元素*/
FD_SET(STDOUT_FILENO,&fdset); /*设置stdout,使集合中包含stdout*/
if(FD_ISSET(STDOUT_FILENO,&fdset)!=0) /*测试stdout是否包含在集合中*/
printf("stdout has been set\n");
else
printf("stdout has not been set\n");
FD_CLR(STDOUT_FILENO,&fdset); /*从位向量中清除stdout*/
if(FD_ISSET(STDOUT_FILENO,&fdset)!=0) /*再次测试*/
printf("stdout has been set\n");
else
printf("stdout has not been set\n");
return 0;
}