gpt4 book ai didi

c - 仅对套接字上的新数据使用 poll() 超时

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:48 25 4
gpt4 key购买 nike

我有一个通过套接字连接的发送器和接收器。当发件人发送某些内容时,我想在 poll() 上使用计时器来了解是否没有从接收方返回确认。在阅读了很多问题(Why does poll keep returning although there is no input?Embedded Linux poll() returns constantlypoll(2) doesn't empty the event queue)之后,我明白 poll() 函数可以返回 1,即使接收方没有发回任何东西,只是因为 read() 函数不会阻塞在套接字的文件描述符上。

但我想使用 poll() 的超时时间来了解套接字上是否没有任何内容。如何让 poll() 函数仅在新数据到达套接字时才返回 1?

这是我的代码示例,以防我做错了什么:

while(1){

rv = poll(ufds, ufds[0].fd +1 , 1000);

if (rv == -1) {
perror("poll");
} else if (rv == 0) {
printf("Timeout occurred! No data after 1 seconds.\n");
} else {
if (ufds[0].revents & POLLIN) {
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
{
die("recvfrom()");
}
printf("ACK = %s \n", buf);
}
if (ufds[0].revents & POLLPRI) {
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
{
die("recvfrom()");
}
}
}
}

TL;DR:此代码从不打印“发生超时!”因为套接字的文件描述符总是准备好的。我可以改变这种行为吗?

非常感谢!

最佳答案

可能已在链接的帖子中得到回答,但基本思想是 pollselect 和其他机制不会在有新消息时告诉您套接字上的数据。正如您正确提到的那样,它们告诉您何时 read() 不会阻塞。

你可以使用 EPOLLET 和 Linux 的 epoll(7) 接口(interface)(其他系统可能有其他等价物)来做你想做的事;但是请记住,这不是可移植的。

正确且可接受的设计是要么完全使用网络缓冲区,要么将部分消息保存在应用程序定义的缓冲区中(即在套接字的缓冲区中)并跟踪您有多少额外数据需要从网络读取。

关于c - 仅对套接字上的新数据使用 poll() 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26517373/

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