I am trying to run a process and read its stdoutput and stderror from a .net6 console app. The code:
public Process Run(string command, string args)
{
var psi = new ProcessStartInfo
{
FileName = command,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
var p = new System.Diagnostics.Process { StartInfo = psi, EnableRaisingEvents = true };
p.ErrorDataReceived += (sender, e) => ...
p.OutputDataReceived += (sender, e) => ...
p.Exited += async (sender, e) =>
{
// this allows to wait until we read both StandardOutput and StandardError asynchronously; without it we get more stdOut data after Exited event...
// https://stackoverflow.com/a/17600012/5033397
await p.WaitForExitAsync();
p.Dispose();
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
return p;
}
It works 99% of the time, but I am getting this error intermittently (might happen once every few hours or so while the app is running on a server):
System.InvalidOperationException: StandardError has not been redirected.
at System.Diagnostics.Process.BeginErrorReadLine()
at ProcessRunner.Run(String command, String args) in /app/ProcessRunner.cs:line 88
This happens both Windows and Linux. Processes being executed with code above:
- iostat
- typeperf
- ffprobe
- ffmpeg
What could be wrong with this setup?