Redirecting Standard Input/Output using the Process Class

2024-01-17 12:18

本文主要是介绍Redirecting Standard Input/Output using the Process Class,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

2001年12月25日 09:21:00

Redirecting Standard Input/Output using the Process Class
Submitted ByUser LevelDate of Submission
Edwin LimaBeginner12/18/2001

Source Code: System.Diagnostic.ProcessCode.zip

When a program starts, a new process (a program in execution) is created by the operating system, and this process is identified by its process Id and also a name. A set of counters are set attached to this process by the OS in order to have some statistics about it.

In .NET, the process component is used to start a new process or even kill or suspend an existing one. Also we can get some statistics about the process already running through the following properties:.

NonpagedSystemMemorySize:
PagedMemorySize:
PagedSystemMemorySize:
PeakPagedMemorySize:
PeakVirtualMemorySize:
PeakWorkingSet
PriorityClass
PrivateMemorySize
PrivilegedProcessorTime

The process component offers static and instance methods. Some very important static methods are:

EnterDebugMode: Put the process in debugging for interaction with the OS.
GetCurrentProcess: Returns the current running process.
GetProcessById: Returns a process instance of an existing process receiving as parameter the process id.
GetProcesses: Returns an array of Process instances of the currently running process in the host machine .
Start: Starts a new process.

The Process Class Methods:
Close: Frees the resources associated with an instantiated process component.
Kill: Terminates a running process
CloseMainWindow: Close a process which a main windows by sending a message to its main window.

The Process Class Properties:

Responding: Gets a value about the current status of a process: true for running false for not Responding.
StandardError: Gets a file descriptor for the standard error in order to be able to redirect to a normal Stream Reader and read as a file..
StandardInput: Gets the standard input of the process as file descriptor in order to be able to redirect and write to it as if writing to a StremWriter.
StandardOutput; Similir as the Standard error but used to read the standard output of the process.
StartInfo: This property has to be set with a ProcessStartInfo instance to pass initialization parameters to the process, before it starts. Altering this process after starting a process has no effect.

The list of properties and methods above show is not exhaustive, you can find some other ones through the help online.

In this example I'll try to illustrate some of the power of this component by starting a normal process (windows app) or also by redirecting the standard error, output and input of a DOS app. Also, you will see how to execute DOS commands by using the process component. You can also extend the example by
reading some of the counters associated to a process and showing them in a window, like the Task Manager app. The let's see the example and some important details about it:

First of all we need to instantiate a ProcessStartInfo class passing as a constructor param the name of the app that we want to launch and to set some parameters to be passed to the Process instances (p):

ProcessStartInfo psI = new ProcessStartInfo("cmd");


The property psI.UseShellExecute was set as false, to be able to redirect the StandardInput, etc. After that, the properties

psI.RedirectStandardInput
psI.RedirectStandardOutput
psI.RedirectStandardError

...are set to true.

To avoid the cmd annoying window we set as true the property psI.CreateNoWindow so no window will be created for the cmd app.Finally we set the p.StartInfo property to the instance of ProcessStartInfo
that we have just created and voila , starts the process.

To be able to capture the p.StandardInput, p.StandardOutput and p.StandardError we get the File Descriptors (StreamReaders and StreamWriter classes) to read the StandardOutput and StandardError and to write to the StandardInput. The read and write operations are performed as we do it in a normal file. (Hmm, does this way of working with the IO remind you the unix world?) The process cmd is closed when we close the p.StandardInput file descriptor.

At the very end we read the p.StandardOutput and p.StandardError file descriptors into the text box. See the complete code of the method that implements the whole stuff.

private void start()
{
Process p = new Process();
StreamWriter sw;
StreamReader sr;
StreamReader err;



ProcessStartInfo psI = new ProcessStartInfo("cmd");
psI.UseShellExecute = false;
psI.RedirectStandardInput = true;
psI.RedirectStandardOutput = true;
psI.RedirectStandardError = true;
psI.CreateNoWindow = true;
p.StartInfo = psI;


p.Start();
sw = p.StandardInput;
sr = p.StandardOutput;
err = p.StandardError;



sw.AutoFlush = true;
if (tbComm.Text != "")
sw.WriteLine(tbComm.Text);
else
//execute default command
sw.WriteLine("dir //");


sw.Close();

textBox1.Text = sr.ReadToEnd();
textBox1.Text += err.ReadToEnd();

}







About the Author:Edwin Lima is a software engineer working for NEC Computers International BV in the Netherlands. Most of his time he's busy with data integration tasks and in his free time he plays around with C# and .NET related stuff (You can contact me at: edwinlima@hotmail.com)



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=3542


这篇关于Redirecting Standard Input/Output using the Process Class的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/616008

相关文章

类型信息:反射-Class

在说反射前提一个概念:RTTI(在运行时,识别一个对象的类型) public class Shapes {public static void main(String[] args) {List<Shape> shapes = Arrays.asList(new Circle(), new Square(), new Triangle());for (Shape shape : shapes

react笔记 8-17 属性绑定 class绑定 引入图片 循环遍历

1、绑定属性 constructor(){super()this.state={name:"张三",title:'我是一个title'}}render() {return (<div><div>aaaaaaa{this.state.name}<div title={this.state.title}>我是一个title</div></div></div>)} 绑定属性直接使用花括号{}   注

Unity Post Process Unity后处理学习日志

Unity Post Process Unity后处理学习日志 在现代游戏开发中,后处理(Post Processing)技术已经成为提升游戏画面质量的关键工具。Unity的后处理栈(Post Processing Stack)是一个强大的插件,它允许开发者为游戏场景添加各种视觉效果,如景深、色彩校正、辉光、模糊等。这些效果不仅能够增强游戏的视觉吸引力,还能帮助传达特定的情感和氛围。 文档

泛型参Class、Class、Class的对比区别

1.原文链接 泛型参Class、Class、Class的对比区别 https://blog.csdn.net/jitianxia68/article/details/73610606 <? extends T>和<? super T> https://www.cnblogs.com/drizzlewithwind/p/6100164.html   2.具体内容: 泛型参数Class、

c++通用模板类(template class)定义实现详细介绍

有时,有两个或多个类,其功能是相同的,仅仅是数据类型不同,如下面语句声明了一个类:class Compare_int { public : Compare(int a,int b) { x=a; y=b; } int max( ) { return (x>y)?x:y; } int min( ) { return (x&... 有时,有两个或多个类,其功能是相同的,仅仅是数

Python方法:__init__,__new__,__class__的使用详解

转自:https://blog.csdn.net/qq_26442553/article/details/82464682 因为python中所有类默认继承object类。而object类提供了了很多原始的内建属性和方法,所以用户自定义的类在Python中也会继承这些内建属性。可以使用dir()函数可以查看,虽然python提供了很多内建属性但实际开发中常用的不多。而很多系统提供的内建属性实际

SpringBoot启动报错Failed to determine a suitable driver class

两种解决办法 1.在Application类上加 ` @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) package com.example.demo3;import org.springframework.boot.SpringApplication;import org.springframewo

easyswoole not controller class match

not controller class match composer.json 注册 App 这个名称空间了吗?执行过 composer dump-autoload 了吗?存在 Index 控制器,但是文件大小写、路径都对了吗? task socket listen fail 注意,在部分环境下,例如 win10 的 docker 环境中,不可把虚拟机共享目录作为 EasySwoole 的 T

JavaBug系列- Failed to load driver class com.mysql.cj.jdbc.Driver in either of HikariConfig class load

JavaBug系列之Mysql驱动问题 Java医生一、关于错误信息二、如何解决问题 Java医生 本系列记录常见Bug,以及诊断过程和原因 Java/一对一零基础辅导/企业项目一对一辅导/日常Bug解决/代码讲解/毕业设计等 V:study_51ctofx 一、关于错误信息 APPLICATION FAILED TO START Description: Fai

【上】java获取requestMapping上所有注解功能实现及取匿名注释类的值及 class com.sun.proxy.$Proxy140 转换出错

java获取requestMapping上所有注解功能实现及取匿名注释类的值及 class com.sun.proxy.$Proxy140 转换出错 1,多人相当然以为类似对象一样直接强转下就可以,结果迎来的是class com.sun.proxy.$Proxy140转换出错【想法很勇敢,现实很骨感】 //Class<A> operatorMappingAnnotationType// 错误