c++ - 是什么导致 poll() 函数出现错误,C++?

标签 c++ sockets

我对套接字编程相当陌生,我正在尝试编写一个程序来获取传入的 TCP 连接并以某种方式管理它们。我不明白为什么下面的代码给我一个“轮询错误”:

int main(int argc, char *argv[]) {
char *port;
struct pollfd connections[MAX_CONNECTIONS];
struct addrinfo addr_hints, *addr_result;
int ret, i;

for (i = 0; i < MAX_CONNECTIONS; ++i) {
    connections[i].fd = -1;
    connections[i].events = POLLIN;
    connections[i].revents = 0;
}

port = "0";

memset(&addr_hints, 0, sizeof(struct addrinfo));
addr_hints.ai_flags = AI_PASSIVE;
addr_hints.ai_family = AF_UNSPEC;
addr_hints.ai_socktype = SOCK_STREAM;
addr_hints.ai_protocol = IPPROTO_TCP;

getaddrinfo(NULL, port, &addr_hints, &addr_result);

connections[0].fd = socket(addr_result->ai_family, addr_result->ai_socktype, addr_result->ai_protocol);

if (connections[0].fd < 0) {
    cerr << "Socket error" << endl;
    return 0;
}

if (bind(connections[0].fd, addr_result->ai_addr, addr_result->ai_addrlen) < 0) {
    cerr << "Bind errror" << endl;
    return 0;
}

if (listen(connections[0].fd, 25) < 0) {
        cerr << "Listen error" << endl;
    return 0;
}

do {
    for (i = 0; i < MAX_CONNECTIONS; ++i)
            connections[i].revents = 0;

    ret = poll(connections, MAX_CONNECTIONS, -1);

    if (ret < 0) {
        cerr << "Poll error" << endl;
        return 0;
    } else {
        //DO SOMETHING
    }

} while(true);
}

MAX_CONNECTIONS 是一个设置为 10000 的常量。 Connections[0] 应该是我正在监听传入连接的描述符。我将端口设置为“0”,因为我想选择一个随机端口。 poll 函数似乎立即失败,产生消息“Poll error”(因此 poll() 基本上小于 0)。我已经检查过,在轮询和绑定(bind)连接[0]之后有一个文件描述符。我不确定我做错了什么,是 getaddrinfo 函数的问题吗?

最佳答案

问题是您的 poll 的文件描述符数组太大。它的最大大小定义为 RLIMIT_NOFILE。对于您的系统来说,这可能是 1024。将 MAXIMUM_CONNECTIONS 减少到该值或更少。

来自民意调查规范:

EINVAL The nfds value exceeds the RLIMIT_NOFILE value.

查看更多信息:http://man7.org/linux/man-pages/man2/poll.2.html

关于c++ - 是什么导致 poll() 函数出现错误,C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39066799/

相关文章:

c++ - 如何在 C++ 中对二维数组进行排序

c++ - 为什么我可以通过指向派生对象的基类指针访问派生私有(private)成员函数?

c - 发送数据包时如何设置iptables标记?

c# - C#.NET套接字tcp begin/endreceive客户端: endreceive reads all bytes,,但是在beginreceive中,缓冲区大小自行更改

Python:如何干净地关闭套接字以避免 'can not assign requested address' 错误(高频)

c++ - 删除图像中的小背景(黑色)区域

c++ - 使用非常量变量作为 constexpr 数组的索引来传递给模板参数

c++ - 在 C++ 中进行简单测试

java - 尝试传输文件时套接字关闭异常

多个服务器可以在一个套接字上与一个客户端通信吗?