.NET Process — avoid deadlock with async reads
If you are working with a child process that writes large amounts of data to its redirected stdout (or stderr), it is advisable to read from it asynchronously.
Why read stdout asynchronously?
A pipe is a connection between two processes in which one process writes data to the pipe and the other reads from the pipe. System.Diagnostics.Process.StandardOutput is an example of a pipe.
A child process may block while it waits for the client end to read from its stdout (or stderr).
When redirected, a process’s stdout may reach its limit, it will then wait for its parent to read some data before it will continue. If the parent process is waiting for all the bytes to be written before it reads anything (synchronous read), then it will wait indefinitely.
The point is: redirected streams have a limited buffer, keep them clear to allow process to complete.
So you may encounter deadlock:
[Deadlock] Pipes have a fixed size (often 4096 bytes) and if a process tries to write to a pipe which is full, the write will block until a process reads some data from the pipe.
If your child process is going to write more data than its buffer can contain, you’ll need to read it asynchronously. This stops a process blocking by ensuring there is space to emit data.
Example: piping a file to lame stdin (Windows)
Use the type command:
$ type file.mp3 | lame --mp3output 64 - "path/to/output.mp3"
Type reads the source file an emits it to its stdout, we’re then piping that directly to lame. In the preceeding example, lame has been instructed to read from stdin and write directly to a file.
To pipe stdout to another process, use something like:
$ type file.mp3 | lame --mp3output 64 - - | another_process
Or redirect to a file:
$ type file.mp3 | lame --mp3output 64 - - > "path/to/output.mp3"
Get a list of running processes (Windows)
Use the query process command.
- Pipeline (Unix)
- Pipes (Windows)
- Buffering in stdio streams
- What is a pipe?
- Avoid blocking reads on both stdout and stderr (MSDN)