首页 Soft PlugIn RAN乱 Dev开发 Info资料 English WAP 留言 登陆 注册
-
Posted by Yippee | 评论(1) | 引用(1) | 阅读2944次
Process.StandardOutput 属性

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# 一个调用外部程序的例子


字体:

Permanant URI永久地址 http://www.shengfang.org/blog/p/ProcessStandardOutput.php
Trackback URI引用地址 http://www.shengfang.org/blog/tb.php?tb_id=1122282148

2005年7月25日17:02星期一  [Dev开发] 追踪此文的RSS
Jarod在 2005年11月1日09:17星期二 评论:
有关程序中调用执行控制台应用程序并交互疑问!
和楼主的文章最后一个问题相似。

输入一个命令,获得输出,判断该输出内容并输入相应命令,再获得输出值...重复以上动作。
我在CSDN论坛上的帖子,麻烦楼主指教
http://community.csdn.net/Expert/topic/4351/4351752.xml?temp=.688534
Emotion
谢谢!
Yippee 回复于 2005年11月1日11:32
请参见 VS.NET PROCESS 输入 输出 模拟 CMD :) 不知道是否可以。没有完善

称呼:    登陆   注册
   不注册,但记住我的信息
邮件:
(非必须)
评论: [UBB代码帮助]
粗体 斜体 下划线 链接 水平线 引用



验证码: 请输入你看见的数字
关闭UBB      提交时自动将内容复制到剪贴板

公告
Fire and Motion!

统计信息
[Yippee]||[统计]||日志:1858
在线: 11||用户: 2577 [列表]
今日:396||到访:2886460
Rss:897736||评论:1605

最新日志

最新评论

友情链接

日历
2008 - 08
     12
3456789
10111213141516
17181920212223
24252627282930
31      

最新引用

搜索

归档

杂项
Get RSS Feed (Version 2.0)
Get Atom Feed (Version 0.3)
编码:  UTF-8