当另一方写入管道时,读取管道是否安全?
fSuccess = ReadFile(
hPipe, // pipe handle
chBuf, // buffer to receive reply
BUFSIZE*sizeof(TCHAR), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped
如果不安全,如何确保在 Windows 中读取管道时另一端没有写入?
fSuccess = ReadFile(
hPipe, // pipe handle
chBuf, // buffer to receive reply
BUFSIZE*sizeof(TCHAR), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped
If not safe, how can I ensure the other side is not writing when reading a pipe in windows?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是对管道的完全合法的操作。管道的一端可以读取和写入管道,而不管另一端发生什么情况。
Yes, this is a perfectly legal operation on the pipe. One end of the pipe can read from and write to a pipe irrespective of what is happening to the other end.
它是完全安全的——管道自动处理缓冲区上所有必要的同步。如果您在其他进程关闭与管道的连接时尝试写入/读取管道(通过显式关闭管道或隐式退出进程),您将收到
ERROR_BROKEN_PIPE
GetLastError
。如果您使用匿名管道,父进程通常会查找此管道以检测子进程何时退出,因此将不再需要处理数据。It's perfectly safe -- pipes handle all the necessary synchronization on the buffers and such automatically. If you try to write to/read from a pipe when the other process has closed its connection to the pipe (either explicitly by closing the pipe, or implicitly by exiting the process) you'll get
ERROR_BROKEN_PIPE
fromGetLastError
. If you're using anonymous pipes the parent process will typically look for this to detect when the child process exited, so there will be no more data to process.