gpt4 book ai didi

c++ - poll(2) 在数据准备就绪时不返回

转载 作者:行者123 更新时间:2023-11-30 01:57:38 25 4
gpt4 key购买 nike

我正在尝试用 C++ 编写套接字抽象。我正在使用 poll() 系统调用来等待数据准备好读取。但是,当我运行我的程序时,如果我将它设置为无限期轮询,则 poll() 永远不会返回,即使我发送套接字数据也是如此。

这是一个简单的程序来说明我的问题。我在 OSX 上使用以下行对其进行编译:clang++ -g -Wall -pedantic -std=c++0x -stdlib=libc++ pollTest.cpp -o pollTest。我正在使用 nc 程序为要连接的程序设置监听套接字。当我运行它时,poll() 调用永远挂起,由于数据已准备好读取而永远不会返回。

#include <poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <unistd.h>
#include <poll.h>
#include <fcntl.h>
#include <cstdlib>
#include <iostream>

void connectSocket(int& fd, std::string hostname, std::string service) {
struct addrinfo hints, *res, *res0;
int error;
int s;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
error = getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res0);
if (error) {
throw error;
}
s = -1;
for (res = res0; res; res = res->ai_next) {
s = socket(res->ai_family, res->ai_socktype,
res->ai_protocol);
if (s < 0) {
continue;
}

if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
close(s);
s = -1;
continue;
}

break; /* okay we got one */
}

if (s < 0) {
throw s;
}
}

int main() {
int socketFileDescriptor = -1;
connectSocket(socketFileDescriptor, "localhost", "9999");

pollfd socketPolls[1];
socketPolls[0].fd = socketFileDescriptor;
socketPolls[0].events = POLLIN | POLLPRI | POLLRDBAND | POLLRDNORM;
poll(socketPolls, 1, -1);
std::cerr << socketPolls[0].revents;
}

关于为什么会发生这种情况的任何想法?我觉得我已经很好地阅读了文档,并且正确地使用了系统调用。 (我没有在这个示例程序中进行错误检查,但我在我的项目中进行了)。任何帮助将不胜感激!

最佳答案

connectSocket 中,您从未将 fd 设置为任何内容,因此在 main 中,socketFileDescriptor 仍然是 -1poll 不会在套接字上找到任何数据。您可能打算统一 sfd。也就是说,我认为您最好返回文件描述符而不是使用引用。

关于c++ - poll(2) 在数据准备就绪时不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18434482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com