Process.StandardOutput
Namespace: System.Diagnostics
Assembly: System (in System.dll)
Syntax
Property Value
Type: System.IO.StreamReader
A StreamReader that can be used to read the standard output stream of the application.
Exceptions
| Exception | Condition |
|---|---|
| InvalidOperationException |
The StandardOutput stream has not been defined for redirection; ensure ProcessStartInfo.RedirectStandardOutput is set to trueand ProcessStartInfo.UseShellExecute is set to false. - or - The StandardOutput stream has been opened for asynchronous read operations with BeginOutputReadLine. |
Remarks
When a Process writes text to its standard stream, that text is normally displayed on the console. By redirecting the StandardOutput stream, you can manipulate or suppress the output of a process. For example, you can filter the text, format it differently, or write the output to both the console and a designated log file.
Note |
|---|
|
To use StandardOutput, you must set ProcessStartInfo.UseShellExecute to false, and you must set ProcessStartInfo.RedirectStandardOutput to true. Otherwise, reading from the StandardOutput stream throws an exception. |
The redirected StandardOutput stream can be read synchronously or asynchronously. Methods such as Read, ReadLine, and ReadToEnd perform synchronous read operations on the output stream of the process. These synchronous read operations do not complete until the associated Process writes to its StandardOutputstream, or closes the stream.
In contrast, BeginOutputReadLine starts asynchronous read operations on the StandardOutput stream. This method enables a designated event handler for the stream output and immediately returns to the caller, which can perform other work while the stream output is directed to the event handler.
Synchronous read operations introduce a dependency between the caller reading from the StandardOutput stream and the child process writing to that stream. These dependencies can result in deadlock conditions. When the caller reads from the redirected stream of a child process, it is dependent on the child. The caller waits on the read operation until the child writes to the stream or closes the stream. When the child process writes enough data to fill its redirected stream, it is dependent on the parent. The child process waits on the next write operation until the parent reads from the full stream or closes the stream. The deadlock condition results when the caller and child process wait on each other to complete an operation, and neither can proceed. You can avoid deadlocks by evaluating dependencies between the caller and child process.
The following C# code, for example, shows how to read from a redirected stream and wait for the child process to exit.
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
The code example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.
There is a similar issue when you read all text from both the standard output and standard error streams. The following C# code, for example, performs a read operation on both streams.
// Do not perform a synchronous read to the end of both
// redirected streams.
// string output = p.StandardOutput.ReadToEnd();
// string error = p.StandardError.ReadToEnd();
// p.WaitForExit();
// Use asynchronous read operations on at least one of the streams.
p.BeginOutputReadLine();
string error = p.StandardError.ReadToEnd();
p.WaitForExit();
The code example avoids the deadlock condition by performing asynchronous read operations on the StandardOutput stream. A deadlock condition results if the parent process calls p.StandardOutput.ReadToEnd followed by p.StandardError.ReadToEnd and the child process writes enough text to fill its error stream. The parent process would wait indefinitely for the child process to close its StandardOutput stream. The child process would wait indefinitely for the parent to read from the full StandardError stream.
You can use asynchronous read operations to avoid these dependencies and their deadlock potential. Alternately, you can avoid the deadlock condition by creating two threads and reading the output of each stream on a separate thread.
Note |
|---|
|
You cannot mix asynchronous and synchronous read operations on a redirected stream. Once the redirected stream of a Process is opened in either asynchronous or synchronous mode, all further read operations on that stream must be in the same mode. For example, do not follow BeginOutputReadLinewith a call to ReadLine on the StandardOutput stream, or vice versa. However, you can read two different streams in different modes. For example, you can callBeginOutputReadLine and then call ReadLine for the StandardError stream. |
Examples
The following example spawns a new user-defined executable and reads its standard output. The output is then displayed in the console.
using System;
using System.IO;
using System.Diagnostics; class IORedirExample
{
public static void Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
// This is the code for the spawned process
Console.WriteLine("Hello from the redirected process!");
}
else
{
// This is the code for the base process
Process myProcess = new Process();
// Start a new instance of this program but specify the 'spawned' version.
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(args[0], "spawn");
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.WaitForExit();
myProcess.Close();
}
}
}
Version Information
.NET Framework
Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
.NET Framework Client Profile
Supported in: 4, 3.5 SP1
.NET Framework Security
- LinkDemand
for full trust for the immediate caller. This member cannot be used by partially trusted code.
Platforms
Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Process.StandardOutput的更多相关文章
- [C#]使用Process的StandardInput与StandardOutput写入读取控制台数据
本文为原创文章.源代码为原创代码,如转载/复制,请在网页/代码处明显位置标明原文名称.作者及网址,谢谢! 开发工具:VS2017 语言:C# DotNet版本:.Net FrameWork 4.0及以 ...
- 如何执行一条命令在C#里面。Process
Download source - 4.15 KB Introduction It is normal practice to open the Windows command prompt and ...
- 使用Process类重定向输出与错误时遇到的问题 (转)
程序中要调用外部程序cmd.exe执行一些命令行,并取得屏幕输出,使用了Process类,基本代码如下: Process process = new Process(); process.StartI ...
- Process启动.exe,当.exe内部抛出异常时,总会弹出一个错误提示框,阻止Process进入结束
public class TaskProcess { [DllImport("kernel32.dll", SetLastError = true)] public static ...
- C# process 使用方法
public static string ExecuteAaptCommand(string appName, string command) { string result = string.Emp ...
- C#启动进程之Process
在程序设计中,我们经常会遇到要从当前的程序跳到另一个程序的设计需求.也就是当前进程创建另一个进程.C#提供了Process使得我们很方便的实现. 1.Process基本属性和方法 Id //进程的Id ...
- C#操作进程(Process)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- Process.start: how to get the output?
1: Synchronous example static void runCommand() { Process process = new Process(); process.StartInfo ...
- C# Process.WaitForExit()与死锁
前段时间遇到一个问题,搞得焦头烂额,现在记录下来,希望对大家有所帮助. 程序里我使用Process类启动命令行,执行批处理文件 'Create.cmd'(当我手工将此文件拖入命令行执行时,一切正常). ...
随机推荐
- Android 架构师技能图谱(转载)
架构与设计 设计模式 重构 技术选型 特性 可用性 性能 包大小 方法数 文档 技术支持 UI架构模式 MVC MVP MVVM 研发工具 集成开发环境 Android Studio Sublime ...
- Atitit 项目管理 提升开发效率的项目流程方法模型 哑铃型 橄榄型 直板型
Atitit 项目管理 提升开发效率的项目流程方法模型 哑铃型 橄榄型 直板型 项目主体三个部分 ui界面,中间层,数据库 按照不同的比重可以分为一下三个模型 哑铃型 橄榄型 直板型 哑铃型 开 ...
- 深入理解Linux内核-进程地址空间
给内核分配内存和给用户态进程分配内存是有区别的:1.内核的优先级最高,如果某个内核函数请求动态内存,不会被延时2.内核信任自己,不必保护措施3.用户态进程对动态内存的请求被认为不是紧迫的,总是被尽量推 ...
- Session的clear方法和flush方法
Session Clear()与 Flush() 解释 1.Clear 方法 无论是Load 还是 Get 都会首先查找缓存(一级缓存) 如果没有,才会去数据库查找,调用Clear() 方法,可以强 ...
- 灾备系统的评判指标:RTO、RPO
RTO(RecoveryTime Object)是指灾难发生后,从IT系统崩溃导致业务停顿之刻开始,到IT系统恢复至可以支持各部门运作,业务恢复运营之时,此两点之间的时间段称为RTO. RPO(Rec ...
- vim学习日志(7):替换、删除文件中的字符
vim全局替换文件: 语法为 :[addr]s/源字符串/目的字符串/[option] 全局替换命令为::%s/源字符串/目的字符串/g [addr] 表示检索范围,省略时表示当前行. 如:“1,20 ...
- 【转】(四)unity4.6Ugui中文教程文档-------概要-UGUI Visual Components
原创至上,移步请戳:(四)unity4.6Ugui中文教程文档-------概要-UGUI Visual Components 3.Visual Components 有新的组件和游戏对象已添加到uG ...
- gradle查看依赖关系并写入到文本文件的命令
gradle dependencies>xx.txt
- 使用PostgreSQL遇到的一个问题[column does not exist]字段不存在:
表结构: 在我上面的表结构中,明明有一个叫做"fromdeviceId"的字段,但是查询的时候却提示找不到该字段: 仔细观察错误信息,发现,我的字段明明是有一个大写字母(fromd ...
- Python爬取中国票房网所有电影片名和演员名字,爬取齐鲁网大陆所有电视剧名称
爬取CBO中国票房网所有电影片名和演员名字 # -*- coding: utf-8 -*- # 爬取CBO中国票房网所有电影片名 import json import requests import ...
Note