允许管道读取碎片消息
如何防止通过命名管道发送碎片消息。它是否像 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两个因素会影响消息是否可以分段:
您必须以原子方式写入消息 - 对整个消息进行一次写入。
如果消息比管道缓冲区大小(不需要很大)长,那么您的消息将被分成一系列位。第一个将填满缓冲区,接下来的几个将是缓冲区大小,最后一个将是剩下的内容。
您也必须自动读取该消息。也就是说,你的阅读量必须足够大,才能一口气读完整个信息。如果您有一个读取器进程(或线程),那么您可能可以从消息开头读取 2 字节长度,然后自动读取其余数据。 (4 字节长度有点过大;最大缓冲区大小通常在 512-5120 范围内,尽管它确实因系统而异。)
复杂性包括如果有多个进程可以在管道上写入,那么在发送超大消息时,其他进程可能会设法将其数据交错到管道中。
严格来说,这适用于基于 Unix 的系统。然而,我的理解是,WinAPI 在这方面密切反映了 Unix。
There are two factors that affect whether messages can be fragmented:
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.