【发布时间】:2011-07-27 22:37:39
【问题描述】:
大多数情况下,这段代码运行良好。但有时当可执行文件运行了一段时间后,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;
}
}
【问题讨论】:
-
你能在
rc == 0的情况下添加一些调试代码吗?记录passedInFileDescriptor的值,timeout和FD_ISSET(mFileDescriptor, &fdset)中的字段;如果这个总结的代码是正确的,就会出现一些可疑的事情,你可能需要更多的数据来尝试确定它。 -
调用 ioctl() 和 tcsetattr() 更改文件描述符的内容。打开文件的公共文件描述符可以在父子之间共享,并且子子可以更改描述符,然后传播到父子。这假设您自己没有进行 ioctl() 或类似的调用。我正在考虑文件的非阻塞行为。
-
文件描述符是否已关闭或到达eof?
标签: c sockets select-function