In this case I launch a application and read its output value using StandardOutput and StandardError and write it to a file.once the process is launched two different threads are launched which reads the output from the stream and set certain strings which are used to write the same into outout file by main thread.Sometimes(Extremely rare scenario) the process.waitforexit() does not return and wait indefinitely.
private Thread outThread = null;
private Thread errThread = null;
private string outputText = "";
private string errorText = "";
private StreamReader outStream = null;
private StreamReader errStream = null;
protected void ReadError()
{
if (errStream != null) {
errorText = errStream.ReadToEnd();
}
}
protected void ReadOutput()
{
if (outStream != null) {
outputText = outStream.ReadToEnd();
}
}
public int launchProcess(string process, string arguments, StringDictionary env, int timeout, string logfile)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.Arguments = arguments;
psi.FileName = process;
psi.UseShellExecute = false;
if (env != null)
{
psi.EnvironmentVariables.Clear();
foreach (string key in env.Keys)
{
psi.EnvironmentVariables.Add(key, env[key]);
}
}
int time = (timeout == -1) ? int.MaxValue : timeout;
if (logfile != null && time != 0)
{
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
}
try
{
Process p = Process.Start(psi);
if (time != 0)
{
if (logfile != null)
{
outStream = p.StandardOutput;
errStream = p.StandardError;
outThread = new Thread(new ThreadStart(ReadOutput));
errThread = new Thread(new ThreadStart(ReadError));
outThread.Start();
errThread.Start();
}
p.WaitForExit(time);
if (logfile != null) try
{
outThread.Join();
errThread.Join();
File.AppendAllText(logfile,
String.Format("Running '{0}' with arguments '{1}'\nStandard Output:\n", process, arguments),
Encoding.UTF8);
File.AppendAllText(logfile, outputText, Encoding.UTF8);
File.AppendAllText(logfile, "\n\nStandard Error:\n", Encoding.UTF8);
File.AppendAllText(logfile, errorText, Encoding.UTF8);
}catch (Exception e){
debugMessage("Error occurred while writing standard output to log: " + e.Message);
}
if (!p.HasExited)
{
throw new ProcessTimedOutException(psi.FileName);
}
return p.ExitCode;
}
return 0;
}
catch (Exception e)
{
debugMessage("Unable to launch process " + process + ". " + e.Message);
return -1;
}
}
Please note that in error case the process returns only after I manually kill the process,so I guess this is some deadlock issue. Can anyone help me figuring out the issue here?
What I have tried:
I have gone through similar questions at
c# - ProcessStartInfo hanging on "WaitForExit"? Why? - Stack Overflow[
^] but cant relate if I have the same issue.