在调用 select 之前,您应该清除 FD 结构并设置您需要的标志。毕竟,当 select 返回时,这些位可能会从 select 更改,并且当您下次执行循环时,它们与以前不同。
这是我用于我目前正在实施的服务器的示例,这肯定有效。
while(sigterm == false)
{
FD_ZERO(&mReaders);
FD_ZERO(&mWriters);
FD_ZERO(&mExceptions);
FD_SET(fileno(stdin), &mReaders);
FD_SET(serversocket, &mReaders);
pret = pselect(FD_SETSIZE, &mReaders, &mWriters, &mExceptions, NULL, &mSignalMask);
nErrorCode _code = errno;
if(pret == 0)
{
// Timeout occured, but we are not interested in that for now.
continue;
}
if(pret < 0)
{
switch(nErrorCode)
{
case EINTR:
cout << "Interrupted: " << pret << " errno: " << nErrorCode << endl;
break;
default:
{
cout << "Unknown retval from pselect: " << pret<< " errno: " << nErrorCode << endl;
}
}
continue;
}
if(FD_ISSET(fileno(stdin), &mReaders))
{
string s;
cin >> s;
cout << "stdin: " << s << endl;
continue;
}
if(FD_ISSET(serversocket, &mReaders))
{
// client connected
}
}