windows中命名管道读写buffer大小的设置问题

windows 管道机制为windows进程之间通信提供了方便快捷的方法,管道的创建方式和使用方法,搜索一下有很多!这里只解释管道中buffer大小的设置问题!

函数源型:

HANDLE WINAPI CreateNamedPipe(
  _In_      LPCTSTR lpName,
  _In_      DWORD dwOpenMode,
  _In_      DWORD dwPipeMode,
  _In_      DWORD nMaxInstances,
  _In_      DWORD nOutBufferSize,
  _In_      DWORD nInBufferSize,
  _In_      DWORD nDefaultTimeOut,
  _In_opt_  LPSECURITY_ATTRIBUTES lpSecurityAttributes
);

这一块msdn中解释还是比较详细的。

The pipe server should not perform a blocking read operation until the pipe client has started. Otherwise, a race condition can occur. This typically occurs when initialization code, such as the C run-time, needs to lock and examine inherited handles.

这个地方提到了阻塞,很多例子上面都会提示大家使用

nOutBufferSize=0;
 nInBufferSize=0;

如果dwPipeMode=PIPE_TYPE_BYTE 模式下
来实现阻塞式读取,这个是不完全正确的,这个地方存在一个隐藏的bug。
设置成0并不是使用系统默认值,而是真的分配了0B的内存空间你或许会有疑问,那我为什么可以传输文件呢?
在MSDN中是这么说的:
 If the remaining pipe write quota is enough to fulfill the request, the write operation completes immediately. If the remaining pipe write quota is too small to fulfill the request, the system will try to expand the buffers to accommodate the data using nonpaged pool reserved for the process. The write operation will block until the data is read from the pipe so that the additional buffer quota can be released.
当空间不够的时候 系统会扩大缓冲区以便来传输数据,并且会阻塞read进程执行直到数据被读完之后才会释放额外的空间,之后进程才会往下走。
如果此时你在read端是按一定字节大小读取,并不是一次性读完的。那么额外的空间此时没有被释放,但是又没有全部被占用,write端是可以继续写的,就变成了一个有缓存机制的pipe通信,这样数据就会读错!

如果在
dwPipeMode=PIPE_TYPE_MESSAGE

模式下基本不会出现上述问题
因为在此模式下会将每次输出信息当成一个UNIT包来发送。
所以buffer大小设置范围,要参考你要输出的信息范围最好是设置成最大可能消息长度。
如果要传输的信息特别大,比如说文件,那么你可以选择多次发包,客户端重新组合。这个地方就需要你去设计传输协议格式了!

转载于:https://www.cnblogs.com/hgd7123/archive/2013/06/06/3120699.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值