我对套接字编程很新,我正在尝试编写一个程序来获取传入的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)。我已经检查过并且在poll和bind之后连接[0]有一个文件描述符。我不确定我做错了什么,这是getaddrinfo函数吗?
答案 0 :(得分:3)
问题是您的poll文件描述符数组太大了。它的最大大小定义为RLIMIT_NOFILE。对于您的系统,这可能是1024。将MAXIMUM_CONNECTIONS降低到此值或更低。
来自投票规范:
EINVAL The nfds value exceeds the RLIMIT_NOFILE value.