gpt4 book ai didi

c - 如何在 C 中刷新 UDP 套接字的输入缓冲区?

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

如何在 C 中刷新 UDP 套接字的输入缓冲区(如果存在的话)?

我正在嵌入式 Linux 环境中工作,并使用 C 来创建一些 native 应用程序。在同一个网络上有几台这样的嵌入式机器,当其中一台发生事件时(我们称之为 WHISTLE-BLOWER),WHISTLE-BLOWER 应该向网络广播地址发送网络消息,以便所有机器上网络(包括 WHISTLE-BLOWER)知道该事件并根据它执行一些操作。 顺便说一下,我正在使用 UDP 套接字......

伪代码如下:

main
{
startNetworkListenerThread( networkListenerFunction );

while( not received any SIGTERM or such )
{
localEventInfo = checkIfTheLocalEventOccured();
broadcastOnNetwork( localEventInfo );
}
}

networkListenerFunction
{
bindSocket;

while( not SIGTERM )
{
// THIS IS WHERE I WANT TO FLUSH THE RECV BUFFER...
recv_data = recvfrom( socket );
if( validate recv data )
{
startExecuteLocalAction;
sleep( 5 );
stopExecuteLocalAction;
}
}
}

期望并希望使用此代码的方式是:

1. LOCAL_EVENT occured
2. Broadcasted LOCAL_EVENT_INFO on network
3. All machines received EVENT_INFO, including the original broadcaster
4. All machines started executing the local action, including the original broadcaster
5. All machines' network listener(thread)s are sleeping
6. Another LOCAL_EVENT2 occured
7. Since all machines' listener are sleeping, LOCAL_EVENT2 is ignored
8. All machines' network listener(thread)s are now active again
9. GO BACK TO 1 / RESTART CYCLE
RESULT = TOTAL 2 EVENTS, 1 IGNORED

它实际工作的方式是:

1. LOCAL_EVENT occured
2. Broadcasted LOCAL_EVENT_INFO on network
3. All machines received EVENT_INFO, including the original broadcaster
4. All machines started executing the local action, including the original broadcaster
5. All machines' network listener(thread)s are sleeping
6. Another LOCAL_EVENT2 occured
7. Eventhough all machines' listener are sleeping; LOCAL_EVENT2 is queued SOMEHOW
8. All machines' network listener(thread)s are now active again
9. All machines received EVENT_INFO2 and executed local actions again, slept and reactivated
10. GO BACK TO 1 / RESTART CYCLE
RESULT = TOTAL 2 EVENTS, 0 IGNORED

tl,dr:发送到已绑定(bind)套接字的数据包/消息/UDP 广播,其父线程在传递时刻处于休眠状态;以某种方式排队/缓冲并在所述套接字上的下一个“recvfrom”调用中传递。

我希望忽略那些 UDP 广播,所以我考虑刷新接收缓冲区(显然不是我作为 recvfrom 方法参数提供的缓冲区),如果它在调用 recvfrom 之前存在的话。我怎样才能做到这一点?或者我应该遵循什么路径?

最佳答案

请注意,“刷新”的概念仅适用于输出。刷新清空缓冲区并确保其中的所有内容都被发送到目的地。对于输入缓冲区,数据已经在其目的地。可以读取或清除输入缓冲区,但不能“刷新”。

如果您只是想确保已经读取了输入缓冲区中的所有内容,那么您正在寻找的是非阻塞读取操作。如果您尝试它并且没有输入,它应该返回一个错误。

关于c - 如何在 C 中刷新 UDP 套接字的输入缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56948874/

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