Monday, February 28, 2011

A problem with process pipe communication in C#

In C#, the Process component communicates with a child process via a pipe. If a child process writes enough data to the pipe to fill the buffer, the child will block until the parent reads the data from the pipe. This can cause deadlock if your application is reading all output to standard error and standard output, for example, using the following C# code.
              Process p = new Process("...", "...");
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();

In this instance, both the parent and the child processes would be blocked, as the filled pipe prevents the child process from completing, while the parent process is waiting indefinitely for the child process to exit. The pipe buffer, in my code, was 4096 bytes. If the output reaches this limit, it would hang.

This problem can be solved by moving the ReadToEnd() before the WaitForExit(), as follows..
              Process p = new Process("...", "...");
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

References:
[1] http://bytes.com/topic/c-sharp/answers/459800-redirect-standard-output-size-limit
[2] http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Diagnostics/types/Process.html

1 comment:

Blogger said...

Did you know that that you can earn money by locking selected sections of your blog or site?
All you need to do is join AdWorkMedia and use their content locking tool.

Blog Archive

Followers