如何利用select函数实现对超时的管理

发布网友

我来回答

1个回答

热心网友

使用select函数的部分代码如下:
//设置超时时间
timeval *ptimeval = new timeval;
ptimeval.tv_sec = 60;
ptimeval.tv_usec = 10;

m_Exit = FALSE;

while( m_Exit != TRUE)
{
select( maxfds, &readfds, &writefds, &exceptfds,ptimeval);
cout << “ time is out…”<< endl;
);
现象:第一次可以等待60秒后,退出Select函数,但是第二次进入Select函数后,瞬间就会退出,根本不会等待60秒,屏幕上“time is out"不间断的出现

原因:调用select之后,readfds的fd_count值由1变为0,所以瞬间返回,每次将readfds的fd_count值设为1,既每次用FD_SET来重置读集合,则功能正常实现

int sockfd;
fd_set fdR;
struct timeval timeout = ..;
...
for(;;) {
FD_ZERO(&fdR);
FD_SET(sockfd, &fdR);
switch (select(sockfd + 1, &fdR, 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() */
}
}
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com