Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program doesn’t terminate when using processes

Using the ProcessStartInfo and Process I would like start a program (e g getdiff.exe) and then read all the output that program produces. Later I will use the data in a more constructive way put right now I just want to print the data to ensure it works. However the program doesn’t terminate as it should. Does anyone se why? Thank you in advanced.

ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;                
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";

Process p = Process.Start(psi);
string read = p.StandardOutput.ReadToEnd();
p.WaitForExit();

Console.WriteLine(p);
Console.WriteLine("Complete");

p.Close();

Changing the program to this got it working correctly:

ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;                
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";

Process p = Process.Start(psi);
StreamReader read = p.StandardOutput;

while (read.Peek() >= 0)
    Console.WriteLine(read.ReadLine());

Console.WriteLine("Complete");
p.WaitForExit();
p.Close();
like image 988
Teletha Avatar asked Oct 20 '25 05:10

Teletha


2 Answers

ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;                
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";

Process p = Process.Start(psi);
StreamReader read = p.StandardOutput;

while (read.Peek() >= 0)
    Console.WriteLine(read.ReadLine());

Console.WriteLine("Complete");
p.WaitForExit();
p.Close();
like image 119
Teletha Avatar answered Oct 21 '25 18:10

Teletha


The MSDN provides a good example how a process input/output can be redirected. ReadToEnd() cannot determine the end of the stream correctly. The MSDN says:

ReadToEnd assumes that the stream knows when it has reached an end. For interactive protocols, in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely and should be avoided.

EDIT: Another reason to avoid ReadToEnd(): A very fast process will cause an exception, because the stream has to be redirected BEFORE the program output any data.

like image 42
DiableNoir Avatar answered Oct 21 '25 19:10

DiableNoir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!