DeadLock Issues in Process.StandardOutput.ReadToEnd();

╄→гoц情女王★ 提交于 2021-01-26 08:00:27

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1475970/deadlock-issues-in-process-standardoutput-readtoend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!