允许管道读取碎片消息

发布于 2024-08-03 11:46:36 字数 102 浏览 4 评论 0原文

如何防止通过命名管道发送碎片消息。它是否像 while 循环检查错误或断开连接一样简单......还是还有更多内容?
(使用 winapi,C 中的命名管道)

谢谢。

How can I protect against fragmented messages being sent through a named pipe. Is it as simple as a while loop checking for an error or disconnect.... or is there more to it?
(using winapi, named pipes in C)

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城孤痞 2024-08-10 11:46:36

有两个因素会影响消息是否可以分段:

  1. 消息长度
  2. 读取长度

您必须以原子方式写入消息 - 对整个消息进行一次写入。

如果消息比管道缓冲区大小(不需要很大)长,那么您的消息将被分成一系列位。第一个将填满缓冲区,接下来的几个将是缓冲区大小,最后一个将是剩下的内容。

您也必须自动读取该消息。也就是说,你的阅读量必须足够大,才能一口气读完整个信息。如果您有一个读取器进程(或线程),那么您可能可以从消息开头读取 2 字节长度,然后自动读取其余数据。 (4 字节长度有点过大;最大缓冲区大小通常在 512-5120 范围内,尽管它确实因系统而异。)

复杂性包括如果有多个进程可以在管道上写入,那么在发送超大消息时,其他进程可能会设法将其数据交错到管道中。

严格来说,这适用于基于 Unix 的系统。然而,我的理解是,WinAPI 在这方面密切反映了 Unix。

There are two factors that affect whether messages can be fragmented:

  1. Message length
  2. Read length

You must write the message atomically - a single write for the whole message.

If the message is longer than the pipe buffer size (which need not be very big), then your message will be fragmented into a sequence of bits. The first will fill up the buffer, the next few will be the buffer size, and the last will be whatever is left over.

You must read the message atomically too. That is, your read must be big enough to get the whole message in one go. If you have a single reader process (or thread), then you probably can read, say, a 2-byte length from the start of the message and then read the rest of the data atomically. (A 4-byte length would be overkill; the maximum buffer size is normally in the 512-5120 sort of range, though it does vary by system.)

Complications include the fact that if there are multiple processes that can write on the pipe, then other processes may manage to interleave their data into the pipe while your oversize message is being sent.

Strictly, this applies to Unix-based systems. However, my understanding is that the WinAPI closely reflects Unix in this area.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文