c++ - select() block 而不是返回超时

标签 c++ linux select

作为背景,我正在编写一个多线程 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/

相关文章:

jquery - 如何使用选择器和过滤器输入文本

c++ - 在 boost multiindexmap 容器中插入条目时崩溃

c++ - 如何读取 beast::websocket 中错误请求的 header ?

c - system() 调用在 C 中返回错误值

c - 在 c 中使用套接字时,FD_SET 和 FD_ISSET 背后的数据结构是什么?

mysql - 查询 select max 混合字符串和整数

c++ - 这些代码与性能有关吗?一个非常快,另一个超过时间限制

c++ - 使用 cmake 构建 Qt 4 项目时出错

检查是否已为特定接口(interface)卸载 TCP 分段

linux - 将项目添加到启动脚本并以特定用户身份运行?