作为背景,我正在编写一个多线程 Linux 服务器应用程序。每个子进程都有一个与之关联的连接,并使用 select()
查看套接字上是否有数据等待读取。
我已经进行了一些搜索,但有一次我找不到对这个问题的任何帮助。
第一次实际发布到 Stack Overflow,如果我的格式不正确,我深表歉意。
//this first line switches my connection to non-blocking.
//select() still fails whether or not this line is in.
fcntl(ChildConnection -> newsockfd, F_SETFL, 0);
struct timeval tv;
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(ChildConnection -> newsockfd, &readfds);
tv.tv_sec = 3; //3 seconds of waiting maximum. Changing this does nothing.
tv.tv_usec = 0;
printf("-DEBUG: Child, About to select() the newsockfd, which is %i. readfds is %i.\n", ChildConnection -> newsockfd, readfds);
//if I feed this a bad descriptor (-1 or something) on purpose, it DOES return -1 though.
int result = select(ChildConnection -> newsockfd + 1, &readfds, NULL, NULL, &tv);
//this commented out line below doesn't even time out.
//int result = select(0, NULL, NULL, NULL, &tv);
printf("-DEBUG: Child, Just select()ed. result is %i. Hopefully that was >= 0.", result);
if (result < 0)
{
DisplayError("ERROR using select() on read connection in MotherShip::HandleMessagesChild: ");
}
else if (result > 0) // > 0 means there is data waiting to be read
{
/* <--- Snipped Reading Stuff here ---> */
}
//so if the code gets here without a result that means it timed out.
不幸的是,第二个打印行(表示它已被选中)从未被打印出来。有谁知道发生了什么或有建议让我尝试调试它?
最佳答案
您在其他地方有阻塞条件。首先让您的 select() 代码在小型测试平台上运行,然后移植它。您在代码中的评论“下面这条注释掉的行甚至没有超时”可证实是不正确的:
$ cat test.c
#include <stdio.h>
#include <sys/select.h>
int main()
{
struct timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
select(0, NULL, NULL, NULL, &tv);
return 0;
}
$ gcc -o test test.c
$ time ./test
real 0m3.004s
user 0m0.000s
sys 0m0.000s
或者,尝试将调试器附加到挂起的进程并查看它被阻止的位置。或者在strace()等里面看...
关于c++ - select() block 而不是返回超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9946261/