select 用法
#include <sys/select.h>
#include <sys/time.h>
int select (int maxfdp1, fd_set *readset, fd_set *writeset,
fd_set *exceptset, const struct timeval * timeout);
Return >0:就绪描述字的正数目
-1:出错
0 :超时
struct timeval{
long tv_sec;
long tv_usec;
}
void FD_ZERO (fd_set *fdset);
void FD_SET (int fd, fd_set *fdset);
void FD_CLR (int fd, fd_set *fdset);
int FD_ISSET(int fd, fd_set *fdset);
int svc()
{
fd_set rfd;
又有一处说如下:
FD_SETSIZE为1024,一个整数占4个字节,既32位,那么就是用包含32个元素的整数数组来表示文件描述符集。
int nfds = 0, maxfd=-1;
struct timeval timeout;
while( 1 )
{
FD_ZERO(&rfd);
FD_SET(g_socket,&rfd);
if( maxfd < g_socket)
maxfd = g_socket;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
nfds = select(maxfd + 1,&rfd,(fd_set*) 0,(fd_set*) 0,&timeout);
if(nfds > 0 ) {
if(FD_ISSET(g_socket,&rfd)){
FD_CLR(g_socket,&rfd);
getTask();
}
}
}
}