DeadLock issues in Process.StandardOutput.ReadToEnd ();

I read that this piece of code can cause a dead end:

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

The deadlock condition can be met 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 will wait indefinitely to exit the child process. the child process will wait indefinitely for parents to read from the full StandardOutput Stream.

But I do not quite understand. I mean, in this case, what is the parent process and which child?

+7
c # process deadlock
source share
2 answers

In short, this can happen:

Appendix A (your code above) starts child process B and redirects standard output. Then A waits for the completion of process B. While A waits for B to exit, B outputs to the output stream (which A redirected). This stream has a limited buffer size. If the buffer is full, it must be empty so that B can continue to write to it. Since A cannot be read until exit B, you may find yourself in a situation where B will wait for the output buffer to be freed, and A will wait for the exit B. Both are waiting for each other to take action, and you have a dead end.

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 most likely lead to a situation where the output stream will be full, so that the child process (in this case "cmd" ) will wait for it to be cleaned, and the code above will wait for cmd to finish.

+11
source share

The parent process is a call to p.Start() . I assume this is your application (caller). Child process p or, in other words, called.

0
source share

All Articles