Process.StandardOutput 属性 获取一个流,用以读取应用程序输出。 要使用 StandardOutput,必须已为 StartInfo 属性的 RedirectStandardOutput 属性指定了 true。否则,读取 StandardOutput 属性将引发异常。 注意 如果要将 StandardOutput 设置为 true,则 StartInfo 属性上的 UseShellExecute 必须为 false。 Process 组件通过管道与子进程通信。如果子进程写入管道的数据多得足以填满缓冲区,则子进程将一直会阻塞到父进程从管道读取数据时为止。如果应用程序将所有输出都读入标准错误和标准输出,这就会导致死锁。例如,下面这段 C# 代码可能有问题。 Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "test.exe"; p.Start(); p.WaitForExit(); string output = p.StandardOutput.ReadToEnd(); 在这种情况下,父进程和子进程都会阻塞,原因是已填满的管道阻止子进程完成,而父进程则在无限期地等待子进程退出。 通过将 ReadToEnd() 移到 WaitForExit() 的前面(如下所示),可以解决此问题。 Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "test.exe"; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); 如果同时重定向标准输出和标准错误,然后试图读取它们(例如使用下面的 C# 代码),则会出现类似的问题。 string output = p.StandardOutput.ReadToEnd(); string error = p.StandardError.ReadToEnd(); p.WaitForExit(); 在这种情况下,如果子进程向标准错误写入任何文本,它就会阻塞该进程,这是因为父进程直到从标准输出读取完后才能从标准错误读取。但是,父进程直到该进程结束后才会从标准输出读取。对于这种情况,建议这样解决:创建两个线程,以便应用程序可以在单独的线程上读取每个流的输出。 [C#] Process myProcess = new Process(); ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("Process_StandardOutput_Sample.exe" ); myProcessStartInfo.UseShellExecute = false; myProcessStartInfo.RedirectStandardOutput = true; myProcess.StartInfo = myProcessStartInfo; myProcess.Start(); StreamReader myStreamReader = myProcess.StandardOutput; // Read the standard output of the spawned process. string myString = myStreamReader.ReadLine(); Console.WriteLine(myString); myProcess.Close(); 我的思路是,先开始一个CMD,然后EXEC函数每次往里面 lock(this) { p.StandardInput.WriteLine(cmd); return p.StandardOutput.ReadToEnd(); } 发送一个命令,读取一个回应,结果每次都是到p.StandardOutput.ReadToEnd();死在那里,也不报告错误。 父进程直到该进程结束后才会从标准输出读取。对于这种情况,建议这样解决:创建两个线程,以便应用程序可以在单独的线程上读取每个流的输出。晕倒?! vs.net c# 一个调用外部程序的例子 字体:大 中 小 |