大多数情况下,这段代码运行得很好。但有时,当可执行文件运行了一段时间后, select() 似乎立即超时,然后进入一种奇怪的状态,它不断被调用,立即超时,一遍又一遍。那么就必须从外部将其杀死。
我的猜测是标准输入超时更改的方式有问题 - 这就是 select 阻塞的原因。
环顾 StackOverflow,大多数人的 select() 问题似乎都可以通过确保每次都使用宏(FD_ZERO 和 FD_SET)重置并使用正确的初始参数进行选择来解决。我认为这些不是这里的问题。
int rc = 0;
fd_set fdset;
struct timeval timeout;
// -- clear out the response -- //
readValue = "";
// -- set the timeout -- //
timeout.tv_sec = passedInTimeout; // 5 seconds
timeout.tv_usec = 0;
// -- indicate which file descriptors to select from -- //
FD_ZERO(&fdset);
FD_SET(passedInFileDescriptor, &fdset); //passedInFileDescriptor = 0
// -- perform the selection operation, with timeout -- //
rc = select(1, &fdset, NULL, NULL, &timeout);
if (rc == -1) // -- select failed -- //
{
result = TR_ERROR;
}
else if (rc == 0) // -- select timed out -- //
{
result = TR_TIMEDOUT;
}
else
{
if (FD_ISSET(mFileDescriptor, &fdset))
{
if(rc = readData(readValue) <= 0)
{
result = TR_ERROR;
}
} else {
result = TR_SUCCESS;
}
}
最佳答案
请注意,“select”的某些实现严格应用规范: “nfds 是三个集合中编号最大的文件描述符,再加 1”。 因此,您最好将“1”更改为“passedInFileDescriptor+1”作为第一个参数。 我不知道这是否可以解决你的问题,但至少你的代码变得更加......呃......“传统”;)
再见
关于c - select() 在长时间运行后立即超时 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5518010/