Process Control

The .NET Framework provides extensive capabilities to manipulate processes on both the local and remote machines. The Process class of the System.Diagnostics namespace provides an association through which to query and control an underlying system process.

Creating New Processes

There are two approaches for creating new system processes using the Process class. Both approaches work only on the local machine; processes cannot be created on remote machines. The first approach is to instantiate a Process object, set the necessary configuring information via the StartInfo property, and call Start on the Process instance. The StartInfo property takes a System.Diagnostics.ProcessStartInfo instance that encapsulates configuration information for the process to be created. This includes details such as

  • The name of the file to execute

  • Command-line arguments to pass to the application

  • Whether the standard error, input, and output streams should be redirected, allowing them to be obtained via the StandardError, StandardInput, and StandardOutput properties of the Process instance (discussed later in this section)

  • Whether an application with a UI should be started minimized or maximized

  • The initial directory where the process should be started

More Info

Consult the .NET documentation for complete details of all the properties that can be configured using the ProcessStartInfo class.

The following code fragment demonstrates starting a new process using a ProcessStartInfo instance as an argument to a Process constructor:

// Create a ProcessStartInfo instance
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "MyApplication.exe";
psi.Arguments = "arg1 arg2";
psi.WorkingDirectory = @"C:Temp";

// Create and start a Process using the ProcessStartInfo instance
Process proc1 = new Process();
proc1.StartInfo = psi;
proc1.Start();

Alternatively, Process provides three static overloads of the Start method that take configuration information as arguments, start a process, and return a Process instance. The following statements demonstrate the use of the static methods to execute an application named MyApplication.exe:

// Create a new process from a file name
Process proc2 = Process.Start("MyApplication.exe");

// Create a new process from a file name with arguments
Process proc3 = Process.Start("MyApplication.exe", "arg1 arg2");

// Create a new process from a ProcessStartInfo
ProcessStartInfo psi = null;
psi = new ProcessStartInfo("MyApplication.exe", "arg1 arg2");
psi.WorkingDirectory = @"C:Temp";
Process proc4 = Process.Start(psi);

The file name passed to the Process doesn’t have to represent an executable file; any file for which the operating system has an extension to application mapping is valid. For example, if passed a file name with the .doc extension, the application associated with .doc files will be launched (for example, Microsoft Word) and the specified document opened.

When finished with a Process instance, the Close method should be called to correctly release the resources consumed by the object; this doesn’t affect the underlying system process.

Obtaining a Reference to an Existing Process

Table A-3 summarizes four static methods provided by the Process class used to obtain references to running processes. With the exception of the GetCurrentProcess method, all of the methods provide overloaded forms to access processes running on a remote Windows machine.

Table A-3. Process Class Static Methods for Obtaining References to Existing Processes

Static Method

Description

GetCurrentProcess()

Returns a Process instance that is associated with the current application

GetProcessById()

Returns a Process instance associated with the specified ID

GetProcesses()

Returns a Process array containing all of the processes currently running

GetProcessesByName()

Same as GetProcesses but returns only those processes with a given name

Terminating Processes

The Process methods summarized in Table A-4 terminate the associated local process; termination of remote processes is not supported.

Table A-4. Process Methods for Terminating Local Processes

Method

Description

CloseMainWindow()

Sends a Close message to the main window of a GUI application to request termination; the target application can choose to ignore the message. The CloseMainWindow method returns true if the message was successfully sent and false if the target process doesn’t have a main window, or if the main window is currently disabled.

Kill()

Causes the immediate termination of a running process. For GUI applications, CloseMainWindow is a better alternative because it allows the application to close down gracefully; however, Kill is the only way to terminate non-GUI applications.

Instances of the Process class remain valid after the system process they represent has been terminated; the HasExited, ExitCode, and ExitTime properties contain information relating to the terminated process.

Information About Existing Processes

The properties of the Process class provide information about the underlying system processes. The first call to a Process property populates the instance with information about the system process, representing a snapshot of the process at the time the property was accessed; this information is cached in the Process instance and won’t be updated until the Refresh method is called.

Table A-5 provides a summary of the commonly used Process properties. Other properties provide details about the resources that the system process is using; consult the .NET documentation for complete details.

Table A-5. Process Properties

Property

Description

BasePriority

Gets the base priority of the system process; individual threads of the process can be prioritized independently but use the base priority initially.

Id

Gets the unique ID of the system process.

MachineName

Gets the name of the machine the system process is running on.

MainWindowHandle

Gets the handle to the main window for processes running on the local machine; if the process doesn’t have a main window, 0 (zero) is returned.

ProcessName

Gets the name of the system process.

ProcessorAffinity

On multiprocessor machines, ProcessorAffinity gets or sets the processors on which threads of the associated process will be scheduled to run; a bit mask is used to specify the processors that can be used.

Responding

Returns true if the UI of the associated process is capable of responding to user input; if the UI is unresponsive, false is returned.

StandardError

Gets a System.IO.StreamReader through which the standard error output can be read from the associated process. The process must be configured to redirect error messages when it is created or an exception is thrown; see Creating New Processes earlier in this section for details.

StandardInput

Similar to StandardError but provides a System.IO.StreamWriter for writing standard input to the system process.

StandardOutput

Similar to StandardError but provides access to the standard output of a process.

StartInfo

Returns a System.Diagnostics.ProcessStartInfo instance that contains the information used to create the system process; the Creating New Processes topic earlier in this section contains an overview of the ProcessStartInfo class.

StartTime

Gets a System.DateTime instance containing the time the system process was started.

Process Synchronization and Events

Two methods of the Process class allow the current thread to synchronize with the state of a given process. The WaitForExit method blocks the current thread indefinitely until the associated process terminates. For processes that have user interfaces, the WaitForInputIdle method blocks the current thread until the process enters an idle state. Both methods provide overloads where a timeout period is specified, after which the method returns false and the blocked thread continues.

The Process class also provides an event mechanism to notify listeners of process termination. To enable events, the Process.EnableRaisingEvents property must be set to true. An event handler can then be registered with the Process.Exited event that will be called when the associated process is terminated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset