词条 | select函数 |
释义 | 概况select()的机制中提供一fd_set的数据结构,实际上是一long类型的数组, 每一个数组元素都能与一打开的文件句柄(不管是Socket句柄,还是其他 文件或命名管道或设备句柄)建立联系,建立联系的工作由程序员完成, 当调用select()时,由内核根据IO状态修改fd_set的内容,由此来通知执 行了select()的进程哪一Socket或文件可读。 操作程序下面具体解释: #include <sys/types.h> #include <sys/times.h> #include <sys/select.h> int select(nfds, readfds, writefds, exceptfds, timeout) int nfds; fd_set *readfds, *writefds, *exceptfds; struct timeval *timeout; ndfs:select监视的文件句柄数,视进程中打开的文件数而定,一般设为你要监视各文件 中的最大文件号加一。 readfds:select监视的可读文件句柄集合。 writefds: select监视的可写文件句柄集合。 exceptfds:select监视的异常文件句柄集合。 timeout:本次select()的超时结束时间。(见/usr/sys/select.h, 可精确至百万分之一秒!) 当readfds或writefds中映象的文件可读或可写或超时,本次select() 就结束返回。程序员利用一组系统提供的宏在select()结束时便可判 断哪一文件可读或可写。对Socket编程特别有用的就是readfds。 宏解释几行相关的宏解释如下: FD_ZERO(fd_set *fdset):清空fdset与所有文件句柄的联系。 FD_SET(int fd, fd_set *fdset):建立文件句柄fd与fdset的联系。 FD_CLR(int fd, fd_set *fdset):清除文件句柄fd与fdset的联系。 FD_ISSET(int fd, fdset *fdset):检查fdset联系的文件句柄fd是否 可读写,当>0表示可读写。 (关于fd_set及相关宏的定义见/usr/include/sys/types.h) socket读写这样,你的socket只需在有东东读的时候才读入,大致如下: ... int sockfd; fd_set fdR; struct timeval timeout = ..; ... for(;;) { FD_ZERO(&fdR); FD_SET(sockfd, &fdR); switch (select(sockfd + 1, &fdR, NULL, NULL , &timeout)) { case -1: error handled by u; case 0: timeout hanled by u; default: if (FD_ISSET(sockfd)) { now u read or recv something; /* if sockfd is father and server socket, u can now accept() */ } } } 所以一个FD_ISSET(sockfd)就相当通知了sockfd可读。 至于struct timeval在此的功能,请man select。不同的timeval设置 使select()表现出超时结束、无超时阻塞和轮询三种特性。由于 timeval可精确至百万分之一秒,所以Windows的SetTimer()根本不算 什么。你可以用select()做一个超级时钟。 |
随便看 |
百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。