views:

410

answers:

2

I read that this portion of code can cause deadlock:

 Process p = new Process();

 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 p.WaitForExit();
 string output = p.StandardOutput.ReadToEnd();

Because

A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.

But I don't quite why. I mean, in this case here, what's the parent process, and what's the child?

A: 

The parent process is the one calling p.Start(). I guess this is your application (the caller). The child process is p or in other words, the callee.

Scoregraphic
+4  A: 

In short this is what may happen:

Application A (your code above) starts child process B and redirects standard output. Then A waits for the B process to exit. While A waits for B to exit, B produces output into the output stream (which A has redirected). This stream has a limited buffer size. If the buffer becomes full, it needs to be emptied in order to B to be able to continue writing into it. Since A is not reading until B has exited, you can end up in a situation where B will wait for the output buffer to be emptied, while A will wait for B to exit. Both are waiting for each other to take action, and you have a deadlock.

You can try the following code to demonstrate the problem:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd";
psi.Arguments = @"/c dir C:\windows /s";
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();

This will (moste likely) produce the situation where the output stream is full so that the child process (in this case "cmd") will wait for it to be cleared, while the code above will wait for cmd to finish.

Fredrik Mörk
Thanks for your lucid explanation.
Ngu Soon Hui