我正在嘗試使用select函數來接受輸入,但如果用戶沒有輸入任何內容,則每2秒鐘執行一次其他操作。下面的代碼在第一次到達select()時等待兩秒鐘,但是一旦它打印出第一個「超時」消息,它就會在不等待2秒的情況下快速地打印出「超時」,基本上進入無限循環。任何人都知道問題是什麼?謝謝你的幫助。C++ select()不等待超時時間
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
const int STDIN = 0;
int main(int argc, int *argv[])
{
struct timeval tv;
fd_set readfds, master;
tv.tv_sec = 2;
tv.tv_usec = 0;
FD_ZERO(&readfds);
FD_ZERO(&master);
FD_SET(STDIN, &readfds);
FD_SET(STDIN, &master);
string buffer = "";
while(buffer != "quit"){
readfds = master;
if(select(STDIN+1, &readfds, NULL, NULL, &tv) == -1) perror("select");
if (FD_ISSET(STDIN, &readfds)){
getline(cin, buffer);
cout << "You entered: " << buffer << endl;
}else
cout << "Timed out.\n" << endl;
}
return 0;
}
他可以使用'memcpy'來複制'fd_set'。每次調用select時,必須逐位重做fd集合並不是一個好主意。 – 2012-02-29 07:02:13
您應該更喜歡使用FD_COPY而不是memcpy。 – 2013-02-13 15:01:15