//设置超时时间
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() */
}
}
}
使用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() */
}
}
}
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)