使用select函数实现IO管理。通过select函数判断套接字是否存在数据、可以写入数据,可以等待多个套接字。
定义:
/* According to POSIX.1-2001 */
#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);
select函数:
int select(
int nfds, //集合中所有文件描述符的范围,即所有文件描述符的最大值+1。windows中不需要
fd_set *readfds, //检查可读性集合
fd_set *writefds, //检查可写性集合
fd_set *exceptfds, //例外数据集合
struct timeval *timeout); //函数返回时间
返回值:
成功时:返回三中描述符集合中”准备好了“的文件描述符数量。
超时: 返回0
错误: 返回-1,并设置 errno
对fd_set的操作
void FD_CLR(int fd, fd_set *set);//清除某一个被监视的文件描述符。
int FD_ISSET(int fd, fd_set *set);//测试一个文件描述符是否是集合中的一员
void FD_SET(int fd, fd_set *set);//添加一个文件描述符,将set中的某一位设置成1;
void FD_ZERO(fd_set *set);//清空集合中的文件描述符,将每一位都设置为0;
网友评论