进程输入、输出、错误流的重定向 .

来源:互联网 发布:vr全景网站源码 编辑:程序博客网 时间:2024/05/17 17:42

转自:http://blog.csdn.net/vodistr03/article/details/6658340

目录(?)[-]

  1. 一同步方式
  2. 二多线程下的异步读取
  3. 三其他
首先,进程涉及的流有三种,输入流StandardInput、输出流StandardOutput、错误流StandardError,三者不可混淆,特别是输出流和错误流更是要注意不可混为一谈!比如在makefile编译过程中执行make命令,如果没有将错误流重定向输出,那么程序是不会显示原本应该打印的错误信息的。

一、同步方式

这里有一个简单编写的小例子,是一个win窗口程序。为点击按钮,在后台启动控制台,按照程序设定输入命令,并将返回的输出打印在文本框中,下面是核心代码——按钮点击的响应函数。这里存在着有诸多问题:

[csharp] view plaincopyprint?
  1. private void button1_Click(object sender, EventArgs e)  
  2. {             
  3.     ProcessStartInfo start = new ProcessStartInfo("cmd.exe");  
  4.     start.CreateNoWindow = true;                //不显示dos命令行窗口  
  5.     start.RedirectStandardOutput = true;  
  6.     start.RedirectStandardInput = true;  
  7.     start.RedirectStandardError = true;  
  8.     start.UseShellExecute = false;              //是否指定操作系统外壳进程启动程序,这里需为false  
  9.     Process p = Process.Start(start);  
  10.     StreamWriter writer = p.StandardInput;  
  11.     writer.WriteLine("ping www.baidu.com");  
  12.     writer.WriteLine("exit");  
  13.   
  14.     StreamReader reader = p.StandardOutput;     //截取输出流  
  15.     StreamReader readerErr = p.StandardError;   //截取错误流  
  16.   
  17.     string line = reader.ReadLine();              
  18.     while (!reader.EndOfStream)  
  19.     {  
  20.         tbResult.AppendText(line+"\r\n");  
  21.         line = reader.ReadLine();  
  22.     }  
  23.     string lineErr = readerErr.ReadLine();  
  24.     while (!reader.EndOfStream)  
  25.     {  
  26.         tbResult.AppendText(lineErr + "\r\n");  
  27.         lineErr = readerErr.ReadLine();  
  28.     }  
  29.     p.WaitForExit();                            //等待程序执行完退出进程  
  30.     p.Close();                                  //关闭进程  
  31.     reader.Close();                             //关闭流  
  32.     readerErr.Close();  
  33. }  

(1)子后台控制台执行命令开始执行至退出,主窗口会不响应用户操作,也就是通常说的阻塞,这可以通过多线程来解决。另建一线程在后台执行,调用进程启动函数,使之不影响主线程。

(2)程序中这种做法的硬伤是极有可能造成错误流输出的异常,当然在本程序中由于不存在错误流,故异常体现不出来。如果执行的是makefile编译的make命令,既有输出流又有错误流,如果想要通过这种方法在界面上同时显示输出和错误信息,是极不靠谱的,容易发生死锁。这个死锁缺陷也是同步读取重定向流的硬伤,如果一定要同时重定向错误流和输出流,最好使用异步读取重定向方式。采用异步的同时,也应采用多线程,因此对控件的操作要依照多线程的规范。下面是msdn的引述:

同步读取操作在读取StandardOutput 流的调用方及写入该流中的子进程之间引入一个依赖项。这些依赖项可能导致产生死锁情况。调用方读取子进程的重定向流时依赖于该子进程。调用方将等待读取操作,直到子进程写入流或关闭流为止。子进程写入足够多的数据以填充重定向流的时间依赖于父进程。子进程将等待下一次写操作,直到父进程读取了全部流或关闭该流为止。当调用方和子进程相互等待对方完成操作时,就会产生死锁情况,使双方都无法继续执行操作。您可以通过计算调用方和子进程之间的依赖项从而避免出现死锁情况。

二、多线程下的异步读取

[csharp] view plaincopyprint?
  1. private void button1_Click(object sender, EventArgs e)  
  2. {  
  3.     Thread th = new Thread(exeFile);  
  4.     th.IsBackground = true;  
  5.     th.Start();              
  6. }  
  7.   
  8. private void exeFile()  
  9. {  
  10.     ProcessStartInfo start = new ProcessStartInfo("cmd.exe");  
  11.     start.CreateNoWindow = true;                //不显示dos命令行窗口  
  12.     start.RedirectStandardOutput = true;  
  13.     start.RedirectStandardInput = true;  
  14.     start.RedirectStandardError = true;  
  15.     start.UseShellExecute = false;              //是否指定操作系统外壳进程启动程序,这里需为false  
  16.     Process p = Process.Start(start);  
  17.     StreamWriter writer = p.StandardInput;  
  18.     writer.WriteLine("ping www.baidu.com");  
  19.     writer.WriteLine("exit");  
  20.     writer.Close();  
  21.   
  22.     p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);  
  23.     p.BeginOutputReadLine();  
  24.     p.WaitForExit();                            //等待程序执行完退出进程  
  25.     p.Close();                                  //关闭进程  
  26. }  
  27.   
  28. void p_OutputDataReceived(object sender, DataReceivedEventArgs e)  
  29. {  
  30.     if (!string.IsNullOrEmpty(e.Data))  
  31.     {  
  32.         showText(tbResult, e.Data);  
  33.     }             
  34. }  
  35.   
  36. private delegate void showTextDelegate(TextBox tb, string line);  
  37. private void showText(TextBox tb, string line)  
  38. {  
  39.     if (tb.InvokeRequired)  
  40.     {  
  41.         showTextDelegate d = showText;  
  42.         object[] a = { tb, line };  
  43.         tb.Invoke(d, a);  
  44.     }  
  45.     else  
  46.     {  
  47.         tb.AppendText(line + "\r\n");  
  48.     }  
  49. }  

三、其他

注意telnet.exe并不支持流的重定向。