title: Kill child process with WaitForExit() when parent process closes
body: <p>I have a c# .netcore application which is interacting with an external command-line-based program (let's call it <code>program.exe</code>), through StandardOutput and StandardInput. <code>program.exe</code> will run forever unless it is specifically told to close (by sending <code>exit</code> to StandardInput).</p>
  <p>The issue is that I need this program to close when mine does (no matter how), but I also need to call <code>Process.WaitForExit()</code> after it has started, in order to flush the output buffer, and actually receive the program's output. I'm therefore also running this entire operation in a separate thread, so that <code>WaitForExit()</code> doesn't block the rest of my application.</p>
  <p>Here's a slighly simplified example of what's going on:</p>
  <pre class="lang-cs prettyprint-override"><code>public static class BackgroundProcess
  {
      //Called by my application to start the associated process in a new thread
      public static void Start()
      {
          Thread worker = new Thread(RunBackgroundProcess);
          worker.IsBackground = true;
          worker.Start();
      }
      static Process backgroundProcess;
      public static void RunBackgroundProcess()
      {
          backgroundProcess = new Process
          {
              StartInfo = new ProcessStartInfo
              {
                  FileName = &quot;program.exe&quot;,
                  Arguments = &quot;start&quot;,
                  UseShellExecute = false,
                  RedirectStandardOutput = true
              }
          }
          backgroundProcess.OutputDataReceived += BackgroundProcess_OutputDataReceived;
          backgroundProcess.Start();
          backgroundProcess.BeginOutputReadLine();
          backgroundProcess.WaitForExit(); //required in order to flush the output buffer
      }
      private static void BackgroundProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
      {
          DoStuffWithData(e.Data);
      }
  }
  </code></pre>
  <p>As far as I can tell, it's a combination of starting the process in a separate thread and the <code>.WaitForExit()</code> which is keeping <code>program.exe</code> open after my application closes: How can I either flush the output buffer without using <code>.WaitForExit()</code>, or ensure that it's still killed when my application is?</p>
  <p>Also please note that this application needs to remain compatible with macOS and Linux, in addition to Windows.</p>