runtime: Process.WaitForExit() hangs forever even though the process has exited in some cases

Setup

Launch a process with stream redirection where that process itself launches a long-running process:

// in the host process (process1.exe)
var process2 = new Process
{
    StartInfo = 
    {
        FileName = "process2.exe"
        UseShellExecute = false,
        RedirectStandardOutput = true
    }
};
process2.OutputDataReceived += (o, e) => Console.WriteLine(e.Data);
process2.Start();
process2.BeginOutputReadLine();
process2.WaitForExit(); // never returns, even though process2 does exit fairly quickly
return; // returns from Main(), exiting

// in process2.exe
Console.WriteLine("Launching process3.exe!");
var process3 = new Process { StartInfo = { FileName = "process3.exe", UseShellExecute = false } };
process3.Start();
process3.Dispose();

// in process3.exe
while (true) // loop basically forever performing background tasks
{
     ...
}

Expected Behavior Process1 receives the output of Process2. Once Process2 has exited, Process1 can move on from its WaitForExit() call. Meanwhile Process3 continues to run.

Actual Behavior WaitForExit() never returns.

Notes I believe the problem is that WaitForExit() waits for EOF to be returned from redirected streams that are being consumed asynchronously. However, I think that Process3 is somehow inheriting the stdio handles from Process2 which prevents EOF from being sent even after Process2 exits.

Note that unlike dotnet/runtime#26165 and dotnet/runtime#27115 , I am observing the behavior on Windows. I’m not sure if the same would happen on Linux.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 39 (29 by maintainers)

Most upvoted comments

Close() StandardOutput&Error of Process2

did the Close of process2 stdout/stderr work for you?

@tmds I don’t think this is a workaround because I am trying to capture the standard output of process2. If I close stdout before waiting for exit, I won’t get the output. If I wait for exit before closing, then the program hangs.