程序在使用进程时不会终止
本文关键字:终止 进程 程序 | 更新日期: 2023-09-27 17:59:40
使用ProcessStartInfo
和Process
,我想启动一个程序(例如getdiff.exe),然后读取该程序产生的所有输出。稍后我将以更具建设性的方式使用数据,现在我只想打印数据以确保它有效。然而,程序并没有按应有的方式终止。有人知道为什么吗?提前谢谢。
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();
将程序更改为这样可以使其正常工作:
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();
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();
ReadToEnd()
无法正确确定流的末尾。MSDN说:
ReadToEnd假设流知道它何时到达终点。对于交互式协议,其中服务器仅在您请求时发送数据,而不关闭连接,ReadToEnd可能会无限期阻止,应该避免。
编辑:避免ReadToEnd()
的另一个原因是:非常快的进程会导致异常,因为在程序输出任何数据之前,必须重定向流。
不确定它是否相关,但您在执行psi.RedirectStandardInput = true;
时没有对生成的流执行任何操作。也许,不知何故,应用程序要求输入流在退出之前"关闭"?所以试试myProcess.StandardInput.Close()
。
试试这个代码,
p.关闭主窗口()