gpt4 book ai didi

c++ - 套接字:我的 select() 函数逻辑具有未定义的行为

转载 作者:行者123 更新时间:2023-11-30 19:43:37 24 4
gpt4 key购买 nike

我实现了一个程序,该程序从一个套接字接收并从另一个套接字发送/接收。

为此,我使用 select() 轮询,在套接字 1 中,我以高数据速率接收数据,而在另一个套接字中,我接收周期性消息并请求从第一个套接字接收数据。

当没有“来自套接字2”的请求将数据从套接字1委托(delegate)给套接字2时,我从套接字1正常接收数据,没有问题。但是,假设我在套接字 1 中接收数据时收到两个请求“套接字 2”,第二个请求会中断数据接收,就好像它无法再跟上速率“速率不高,实际上只有 150 Hz” 。

我在 main() 中所做的伪代码:

fd_set readfds, rd_fds, writefds, wr_fds;
struct timeval tv;

do
{
do
{
rd_fds = readfds;
wr_fds = writefds;
FD_ZERO (&rd_fds);
FD_SET (sock1, &rd_fds);
FD_SET (sock2, &rd_fds);
FD_SET (sock1, &wr_fds);
tv.tv_sec = 0;
tv.tv_usec = 20;
int ls = sock2 + 1;
rslt = select (ls, &rd_fds, &wr_fds, NULL, &tv);
}
while (rslt == -1 && errno == EINTR);


if (FD_ISSET (sock1, &rd_fds))
{
rs1 = recvfrom (sock1, buff, size of the buff, ....);
if (rs1 > 0)
{
if (rs1 = alive message)
{
/* system is alive; */
}
else if (rs1 == request message)
{
/* store Request info (list or vector) */
}
else {}
}
}

if (FD_ISSET (StructArg.sock2, &rd_fds))
{
rs2 = recv (sock2, ..., 0);
if (rs2 > 0)
{
if ( /* Message (high rate) is from sock 2 */ )
{
/* process this message and do some computation */

int sp1 = sendto (sock1, .....);

if (sp1 < 0)
{
perror ("Failed data transmission ");
}
else
{
/* increase some counters */
}
}
}
}

if (FD_ISSET (sock1, &wr_fds))
{
/*
if there info stored in the list
do some calculaitons then send to sock 1
*/
if (sendto (sock1, ... ...) < 0)
{
perror ("Failed data transmission");
}
else
{
/* increase counter */
}

}

FD_CLR (sock1, &rd_fds);
FD_CLR (sock2, &rd_fds);
}
while (1);
再次,问题是,如果从 sock2 接收到请求,为什么从 sock1 接收会被中断,而我从 sock1 接收(快速消息)时,我希望根据消息中的时间戳在输出中交错消息。

最佳答案

请注意,几乎所有套接字函数都可以阻止执行,除非您使用 O_NONBLOCK 选项创建套接字:

http://pubs.opengroup.org/onlinepubs/009695399/functions/sendto.html

你还必须处理recvfrom只给你部分读取的情况 - 除非你使用MSG_WAITALL:

http://pubs.opengroup.org/onlinepubs/009695399/functions/recvfrom.html

就我个人而言,我会使用多线程实现,它可以让线程坐下来等待每个套接字上的数据。

关于你的最后一个问题:

why does receiving from sock1 is interrupted if a request is received from sock2, while i am receiving from sock1 (fast messages), i expect interleaved messages in the output based on the timestamps in the message.

您是网络堆栈实现的奴隶,并且几乎无法保证一个套接字上相对于另一个套接字的数据发送或接收。您只能保证套接字内的数据正确排序。

关于c++ - 套接字:我的 select() 函数逻辑具有未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449444/

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