简体   繁体   English

如果管道已满,进程将写入管道块吗?

[英]Will a process writing to a pipe block if the pipe is full?

I'm currently diving into the Win32 API and writing myself a wrapper class for CreateProcess and CreatePipe . 我目前正在研究Win32 API,并为自己编写CreateProcessCreatePipe的包装器类。 I was just wondering what will happen if a process that I opened writes too much output for the pipe buffer to hold. 我只是想知道如果我打开的进程写的输出太多而无法容纳管道缓冲区,将会发生什么情况。 Will the process wait until I read from the other end of the pipe? 这个过程会一直等到我从管道的另一端读取吗? The Remark of the CreatePipe function suggests so: CreatePipe函数的备注建议如下:

When a process uses WriteFile to write to an anonymous pipe, the write operation is not completed until all bytes are written. 当进程使用WriteFile写入匿名管道时,直到所有字节都写入后,写入操作才会完成。 If the pipe buffer is full before all bytes are written, WriteFile does not return until another process or thread uses ReadFile to make more buffer space available. 如果在写入所有字节之前管道缓冲区已满,则WriteFile不会返回,直到另一个进程或线程使用ReadFile提供更多缓冲区空间为止。

https://msdn.microsoft.com/en-us/library/windows/desktop/aa365152%28v=vs.85%29.aspx https://msdn.microsoft.com/en-us/library/windows/desktop/aa365152%28v=vs.85%29.aspx

Let's assume I open a process with CreateProcess , then use WaitForSingleObject to wait until the process exits. 假设我使用CreateProcess打开一个进程,然后使用WaitForSingleObject等待该进程退出。 Will the process ever exit if it exceeds the buffer size of its standard output pipe? 如果进程超出其标准输出管道的缓冲区大小,该进程是否会退出?

WaitForSingleObject on a process with redirected output is indeed a deadlock. 具有重定向输出的进程上的WaitForSingleObject确实是一个死锁。 You need to keep the output pipe drained in order to let the child process run to completion. 您需要保持输出管道排空,以使子进程运行完成。

Generally you would use overlapped I/O on the pipe and then WaitForMultipleObjects on the handle pair 1 (process handle, pipe read event handle) in a loop until the process handle becomes signaled. 通常,您将在管道上使用重叠的I / O,然后在循环中在句柄对1 (进程句柄,管道读取事件句柄)上使用WaitForMultipleObjects ,直到发出信号为止。

Raymond Chen wrote about the scenario when the input is also piped: 雷蒙德·陈(Raymond Chen)在输入也通过管道传递时,描述了该场景:


1 As Hans commented, there can be more than one output stream. 1正如汉斯所说,可能有不止一个输出流。 stdout , stderr are typical, even more are possible through handle inheritance. stdoutstderr是典型的,甚至可以通过句柄继承实现更多。 Drain all the pipes coming out of the process. 排干从过程中出来的所有管道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM