在迴圈中使用Select 函式,進行等待超時的使用注意點
目的:設定一個時間值,如果超出這個時間值,例如60秒,Select函式退出
使用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() */
}
}
}