Overview
This article discusses the following:
- Background on processes
- How Windows handles processes
Process
class operations System.Diagnostics
class
Summary
Managing a process in older versions of Visual Basic was a tedious thing. In order to achieve results, you had to write a series of steps, a lengthy series of API calls which would help in getting information about the processes running on your system, in managing processes etc. With the advent of the .NET technology, this work became easier. In .NET, you have to import the System.Diagnostics
namespace. This namespace allows you to interact with system processes, event logs, and performance counters.
This article gives you a brief introduction of how the Windows OS handles processes, methods, definitions, and also explains the way it reacts with .NET. A second article will show you how to work with the Process
class, and get memory and thread information about running processes.
Contents
This is the first article in a series of two. The purpose of this article is to provide an introduction to the basic concepts of processes, and to explore the Process
class in .NET. The first part explores the basic explanation about the functionalities of a process in such a way that they could be useful for managing application processes on your computer, either in a local or remote machine. The next article will show the usage of processes, and their various functionalities used through the .NET technology. Also, it will show you how to develop a simple program that will use the Process
class, memory, and thread information about the running processes.
Simply, a process describes a running application in your local or remote running computer. The key parts of the process functionalities that we will discuss are:
- Displaying information about an application or a service. The
Process
class in .NET provides information about all the processes running on your computer. For example, you can handle information in a process such as PID, handle count (a handle is a value used to uniquely identify a resource), image name, memory usage, faults etc. - Managing operations. This means that you can manage a process in different ways such as start, stop, monitoring and controlling a process etc. This allows you to manage each process separately through the program.
- How to handle process in .NET. This explains about the
System.Diagnostics
namespace and the Process
class component definitions, functionalities, and implementations.
Summary
A process can manage the entire operation of a computer. The functionality of each process may be either managing the operating system performance, or managing threads, and so on. It has the capability to communicate and access local and remote processes in a network or local computer. A process may be a program that you start as a user or a system process on your computer, which may be either from a local or remote network service.
Each process enables you to manage various process operations such as start, stop, monitoring and controlling etc. Each process has a unique identification number, called a Process ID (PID). A process class helps to monitor system processes across the network, and helps to start and stop local or remote system or user processes.
You can operate a process in different ways. These operations are:
- Start. This means that a process can be started by you. You can start a process which may be either not started or stopped.
- Stop. This means that a running process on your computer can be stopped by you at any time. The stopped process can further continue.
- Monitoring. This means that the particular process can be monitored so that you will be able to identify the various status of processes such as CPU usage/time, PID, start and end time, threads etc.
- Controlling. You can control a process allowing it through the various operations such as start, stop, pause, destroy etc.
What is a Process?
What is a process? The simple description of a process is a running application or a program on your computer. As you know, the easiest way to view the processes running on your system is to just press Ctrl-Alt-Delete. It will bring up the Windows Task list Manager on your computer. If you click on the Processes tab (second tab) on the Task Manager, you will be able to view the list of all the processes running on your system.
You can see that the processes displayed on your computer may be either from an active user, system, local or network services. Each process is identified by a Process ID called PID. It helps a process to assign specific allocation of resources on the system. Apart from this, there are other attributes that are associated with the process. Some of these attributes are image name, user name, session ID etc.
Figure 1 shows how the process attributes list is displayed while you view the task list manager in a Windows OS:
Figure1. Processes running in your local or network computer
Each process is associated with different properties on your computer. You can see some of the processes listed using the Windows process manager, shown in Figure 1. The properties of the process will give information about a particular process. And also you can monitor running processes based on any of the following counters.
Table 1 lists the process field property descriptions.
Process Property | Description |
---|
Image Name | The name of a process running in your system. |
PID (Process Identifier) | A unique identifier of each process, which distinguishes between different processes (just like a primary key concept in DBMS). |
User Name | The name of the user under whose account the current process executes, or whose Terminal Services session owns the process. Note that the counter is available only when Terminal Services is installed. |
Session ID | A session ID of a process from the Terminal Services. Note that the session counter is available only when Terminal Services is installed. |
CPU | This field denotes the percentage of time that a process used the CPU since the last update. |
CPU Time | CPU Time determines the total processor time, in seconds, used by a process since it started. |
Memory Usage | It determines the total memory of the number of pages currently resident in the memory of a process, which is denoted in kilobytes. The number of pages currently resident in memory is also termed as the current working set. |
Peak Memory Usage | This field identifies the total peak amount of physical memory resident in a process since it started. |
Memory Delta | This field identifies the total change in memory, in kilobytes, for the process since the last update. |
Page Faults | This field identifies the total number of times data has to be retrieved from disk (also called an interrupt) for a process because it was not found in memory and thus, its value accumulates from the time the process started. |
PF Delta | PF Delta field identifies the change in the number of page faults since the last update. |
NP Pool | NP Pool means Non Paged Pool, which is the amount of memory used by a process, in kilobytes. It never allows the operating system to be paged to disk. Paging is the moving of infrequently used parts of a program's working memory from RAM to another storage medium, such as a hard disk, CD etc. It usually will be the hard disk. |
Base Priorities | Base Priorities allows the user to view and change base priorities, with which we can define a precedence ranking that identifies process threads order, which are scheduled for the processor.
A queue priority will be either of public or private type. The public queue priority in a Message Queuing can be set to the base priority, in which the range starts from -32,768 to 32,767. The default priority is always 0 in a public queue. Private queues do not support base priority.
Note: the order of routes and delivering messages using Message Queuing is prioritized first by base priority and then by message priority.
|
Handles | In Task Manager, the number of object handles in a process' object table. |
Threads | In Task Manager, the number of threads running in a process. |
User Objects | An object from the Window Manager, which includes windows, menus, cursors, icons, hooks, accelerators, monitors, keyboard layouts, and other internal objects. In Task Manager, the number of USER objects currently being used by a process. |
GDI Objects | Objects from the Graphics Device Interface (GDI) library of the Application Programming Interfaces (APIs) for graphics output devices. In the Task Manager, the number of GDI objects currently used by a process. |
I/O Reads | In Task Manager, the number of read input/output operations generated by a process, including file, network, and device I/Os. I/O Reads directed to CONSOLE (console input object) handles are not counted. |
I/O Writes | In Task Manager, the number of write input/output operations generated by a process, including file, network, and device I/Os. I/O Writes directed to CONSOLE (console input object) handles are not counted. |
I/O Other | In Task Manager, the number of input/output operations generated by a process that are neither a read nor a write, including file, network, and device I/Os. An example of this type of operation would be a control function. I/O Others directed to CONSOLE (console input object) handles are not counted. |
I/O Read Bytes | In Task Manager, the number of bytes read in input/output operations generated by a process, including file, network, and device I/Os. I/O Read Bytes directed to CONSOLE (console input object) handles are not counted. |
I/O Write Bytes | In Task Manager, the number of bytes written in input/output operations generated by a process, including file, network, and device I/Os. I/O Write Bytes directed to CONSOLE (console input object) handles are not counted. |
I/O Other Bytes | In Task Manager, the number of bytes transferred in input/output operations generated by a process that are neither a read nor a write, including file, network, and device I/Os. An example of this type of operation would be a control function. I/O Other Bytes directed to CONSOLE (console input object) handles are not counted. |
Base Priority | A precedence ranking that determines the order in which the threads of a process are scheduled for the processor.
For Message Queuing, a property that specifies the queue's priority in a public queue. You can set the base priority from -32,768 to 32,767; the default priority is 0. Private queues do not support base priority. Message Queuing routes and delivers messages first by base priority, then by message priority.
|
CPU Usage | In Task Manager, the percentage of time that a process uses the CPU since the last update. On the Task Manager Process tab, the column heading is CPU. |
Memory Usage Delta | In Task Manager, the change in memory, in kilobytes, used since the last update. |
paged Pool | The system-allocated virtual memory that has been charged to a process and that can be paged. Paging is the moving of infrequently-used parts of a program's working memory from RAM to another storage medium, usually the hard disk.
In Task Manager, the amount of system-allocated virtual memory, in kilobytes, used by a process.
|
Non-paged Pool | Operating system memory that is never paged to disk. Paging is the moving of infrequently used parts of a program's working memory from RAM to another storage medium, usually the hard disk. In Task Manager, the amount of memory used by a process, in kilobytes. |
Virtual Memory Size | In Task Manager, the amount of virtual memory, or address space, committed to a process. |
Table 1: Process Field Properties
You have seen the basic stuffs related to process information. If that is so, what is a thread and how is it associated with a process. Simply, a thread is a unit of process which runs independently of other parts of a computer. This means a process may be associated with one or more threads. Every process should have at least one thread. Generally speaking, a thread allows your program to run in a separate memory process and it allows the isolation of different applications or programs on your computer. Thus, process applications can not directly affect each other's operations.
A thread is an execution pointer, so that a Windows application should make sure which line of the program is running. It follows a single path of execution through a program and is the fundamental unit scheduled by Windows. The movement of the execution pointer will be based on your program usage. Every application has its own primary thread, which manages the thread execution. This ability to run many programs at once (is called multitasking) and the operating system can keep multiple programs in memory at once and keep a chance to run each of the application.
Figure 2 shows how the execution pointer of a thread starts.
Figure 2. How execution pointer in a thread starts in various ways.
For more details about processes, services, and threads, visit MSDN.
How VB.NET and VB 6.0 behave to create multiple threads?
As we discussed earlier, each process is identified by its own unique process ID, which may have zero or more windows associated with it. Each process may contain one or more associated threads, which can be thought of as a stream of executing code, which denotes the field “threads”.
Visual Studio .NET allows users to create multiple threads of processes, but the older versions of Visual Studio doesn’t. In the old version of Visual Studio, it was not possible to create a multi-thread process. It is easy to manage the collection of modules associated with a particular process in .NET, which is an important part of designing a deployment strategy. For example, every Visual Basic 6.0 program requires the VB 6.0 run-time .exe as well as a number of DLLs. You can see these differences in Table 2.
Attributes | Visual Basic 6.0 | Visual Basic .NET |
---|
Multiple threads of a process | Doesn’t allow | Allows users to create multiple threads of a process. |
Run-time files | It requires the VB 6.0 run-time .exe as well as a number of DLLs. | It needs the .NET Framework. |
Table 2: How threads are managed in VB 6.0 and .NET
Operations, priority queues, and monitoring a Process in the Windows OS
There are various controlling activities that are associated with each process on your computer. See Table 3 for the details of these activities. You can destroy, debug, or even set the priorities of a process.
Process Operation | Description |
---|
End Process | This option allows you to end a selected process. You must be careful before ending a process; otherwise you may lose unsaved data. |
End Process Tree | This operation terminates the current process and any processes which were directly or indirectly started by it. This means, this operation terminates the current and its associated processes. You must be careful in forcefully terminating processes, which can cause data loss and system instability. |
Debug | This operation allows you to attach the debugger in a selected process. You must be careful in debugging a process which may result in loss of data. |
Set Priority | Set Priority allows you to change the priority of a running program or a process, which makes you change the priority of a process; it can make a program run faster or slower. A precedence ranking determines the order in which the threads of a process are scheduled for the processor. |
Set Priority Realtime | This operation will set the priority of a process to Realtime. You must be aware of changing the priority class of the process as it may cause undesired results including system instability. |
Set Priority High | Change the priority of a process to make it run faster. |
Set Priority AboveNormal | Change the priority of a process to make it run above normal. |
Set Priority Normal | The priority of a process to be made as normal like other processes. |
Set Priority BelowNormal | Change the priority of a process to make it run below normal. |
Set Priority Low | Change the priority of a process to make it run lower. |
Table 3. Process Operation
Figure 3 shows the different priority queues and various other operations of a process called “ustation.exe” (Ustation.exe is one of the CAD software applications by Bentley Software systems).
Figure 3: Process Operations on the CAD software Microstation executable file (ustation.exe)
Difference between a process and a service
A process is any piece of software that is running on a computer. Some processes are services in that they start up when the computer starts. No user has to log on to start them. An "application" is generally a process that a user has to start.
Each service on your computer has the ability to start and stop local system processes. It provides access to a process that is running on a computer. Figure 4 shows various monitoring operations associated with services:
Figure 4. Start, Stop, Pause services in Windows XP
You must have the appropriate permissions on your system to start, stop, pause, restart, and disable services. Some of the permissions are listed below:
Table 4: Permissions that can be set for a process
Permission | Allows you to |
---|
Full Control | Perform all functions. This permission automatically grants all service permissions to the user. |
Query Template | Determine the configuration parameters associated with a service object. |
Change Template | Change the configuration of a service. |
Query Status | Access information about the status of the service. |
Enumerate Dependents | Determine all of the other services that are dependent on the specified service. |
Start | Start a service. |
Stop | Stop a service. |
Pause and Continue | Pause and continue the service. |
Interrogate | Report the current status information for the service. |
User-Defined Control | Send a user-defined control request, or a request that is specific to the service, to the service. |
Delete | Delete a service. |
Read Permissions | Read the security permissions assigned to the service. |
Pause and Continue | Pause and continue the service. |
Change Permissions | Change the security permissions assigned to the service. |
Take Ownership | Change a security key or change permission on a service that is not owned by the user. |
A Look at the Process Class
The Process
class helps you to access local and remote processes running on your computer. It allows you to manage to start and stop local system processes. In earlier versions of Visual Basic, it was a lot of lines of code, and also lengthy series of API calls were needed to achieve this result. Some of the functionalities of the Process
class are listed in Table 5.
In order to get detailed knowledge about process threads and modules, you need to use the ProcessThread
and ProcessModule
classes.
Process class functionalities |
---|
Start local system processes. |
Stop local system processes. |
Monitor system processes across the network. |
Retrieve lists of running processes based on their computer name, the process ID, or even the process name. |
View information about a process that currently has access to the processor. |
Get information of process threads and modules using the ProcessThread and ProcessModule classes. |
The ProcessStartInfo class allows you to specify a variety of elements with which to start a new process, which will let you manage the following:
- Input
- Output
- Error streams
- Working directories
- Command line verbs and arguments
|
Figure 5: Process Class Hierarchy
The Process
class in .NET is the successor to the Shell command in Visual Basic 6.0. If you need to start an application with parameters, or get notified when it exits, this class provides the power and information you need.
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Diagnostics.Process
Public Class Process
Inherits Component
public class Process : Component
public __gc class Process : public Component
public class Process extends Component
System.Diagnostic.Process class
The System.Diagnostic.Process
class allows you to gain access to information regarding a process, and manage various operations of a process. The System.Diagnostics
namespace allows you to interact with system processes, event logs, and performance counters. The Process
class allows the following operations:
- Starting of processes
- Stopping of processes
- Controlling applications
- Monitoring applications
Figure 6: System.Diagnostic
Class
The System.Diagnostic.Process
class is used for managing various operations of a process such as starting, stopping, controlling, and monitoring applications. For example, you will be able to get a list of running processes, and start a new process by calling an executable, or even register a file extension.
The BasePriority
function of the process allows you get the base priority of the associated process, which is already described above. The Handle
property allows you to get the associated process’ native handle into your program. Some of the process attributes are listed in Table 6.
Process attributes | Associated Functions in .NET |
---|
Image Name | ProcessName() |
PID (Process Identifier) | ID |
User Name | Get from StartInfo() |
Session ID | Get from StartInfo() |
CPU Time | TotalProcessorTime() |
Peak Memory Usage | PeakPagedMemorySize() |
Base Priorities | PriorityClass() |
Handles | HandleCount() |
Threads | Threads() |
I/O Reads | StandardInput()
StandardOutput()
StandardError()
|
I/O Writes |
I/O Other |
I/O Read Bytes |
I/O Write Bytes |
I/O Other Bytes |
Base Priority | BasePriority() |
Paged Pool | PagedMemorySize() |
NP Pool | NonpagedSystemMemorySize() |
Virtual Memory Size | VirtualMemorySize() |
Table 6. Windows process attributes in .NET
Process Component
A Process
component allows you to obtain a list of local, network, or system processes running on your computer. The Process
component is useful for starting, stopping, controlling, and monitoring applications, in such a way that it is possible to create applications that allow you to view and manage processes on your computer. For example, you might use an instance of a Process
for getting the information about a set of threads, the number of processes running, the loaded modules (such as DLL and exe files), memory and CPU information such as the amount of memory a process is using etc. Based on this result, you will be able to manage a program based on your requirements. Figure 7 shows the various attributes associated with a process.
Figure 7. Process
component attributes
Note: Each attributes of the Process
component is self-explanatory. There is no need to explain each of them separately.
Some of the important properties of the Process
component are discussed below:
Handle(), HasExited, ExitCode, ExitTime Methods
PID or the process identifier field uniquely identifies each process in your computer. It is just like a primary key in the database. The Handle
property of the Process
component helps to identify a resource. The ExitCode
method allows to identify whether a process has existed from the system. This value will be either zero for success or a nonzero for error code. The ExitTime
method allows you to find out the process exit time on your computer. Handles are an extremely valuable resource, so leaking handles is more virulent than leaking memory. If you want to detect if a process exists or not, you can use the method HasExited
.
GetProcesses() Method
The GetProcesses
method retrieves an array of Process
class components. It returns all processes currently running on the system. This means you would be able to loop through all the running processes in your computer. Using the process of iteration through the list of processes, by traversing the array or collection, will allow you to retrieve the properties and collections associated with each process. Once you have an instance of a process, there are several properties such as threads, process information, memory usage information, and so on that you have access to.
See the following picture to see all the properties and events associated with the GetProcesses()
method. There is a lot of information you can retrieve from a Process
object. Here are just a few of them.
VB.NET
Imports System.Diagnostics
Public Class getProcesses
Dim clsProcess() As Process = _
System.Diagnostics.Process.GetProcesses()
updateListView()
For intLength As Int16 = 0 To clsProcess.Length - 1
Dim objitem As New ListViewItem(clsProcess(intLength).Id, 0)
objitem.SubItems.Add(clsProcess(intLength).ProcessName)
objitem.SubItems.Add(clsProcess(intLength).BasePriority)
lvwProcInfo.Items.Insert(intLength, objitem)
Next
End Process
C#
Using System.Diagnostics;
System.Diagnostics.Process[] clsProcess =
System.Diagnostics.Process.GetProcesses();
ProcessStartInfo() Method
The ProcessStartInfo
class allows you to specify a variety of elements or data such as the name of document or an executable program, to start a new process. It has the following functionalities:
- Input
- Output
- Error streams
- Working directories
For example, the following program helps you to print a document from Microsoft Word without opening the Word application.
C#
using System.Diagnostics;
namespace MyProcessSample
{
public class WordAutoPrint
{
public void PrintDoc()
{
Process myProcess = new Process();
myProcess.StartInfo.FileName =
myDocumentsPath + "\\MyFile.doc";
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
}
}
GetCurrentProcess(), GetProcessById(), GetProccessesByName(), and GetProcesses() Methods
The GetCurrentProcess
method will return process information representing the process in which it is running. You can also get an instance of a process based on its name or ID, using the GetProcessesByName
and GetProcessByID
methods. For example, if you would like to know how many instance of “Calculator” are running on a specific computer, you need to get the list of all the processes, from which you need to filter out the “Calculator” process, using the command GetProcessName
. GetProcessName
will allow you to get all the instances of a particular application running on the local computer. Say, if you have multiple processes of “Calculator” on your local computer, it will filter out only the “Calculator” processes.
The GetProcessByID
gets a process on the local computer, using the process ID. It actually filters out a process using process the ID or the PID value.
VB.NET
Dim p1 As System.Diagnostics.Process _
= System.Diagnostics.Process.GetCurrentProcess()
Dim p2 As System.Diagnostics.Process() = _
System.Diagnostics.Process.GetProcessesByName("NOTEPAD")
Dim p3 As System.Diagnostics.Process = _
System.Diagnostics.Process.GetProcessById(15)
C#
using System;
using System.Diagnostics;
Process currentProcess = Process.GetCurrentProcess();
Process [] localByName = Process.GetProcessesByName("notepad");
Process localById = Process.GetProcessById(1234);
WaitForExit Method
The WaitForExit
method allows you to launch a process and wait until it exits. I allows you to launch an external program when you use this method from a form.
Private Sub btnWaitForExit_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnWaitForExit.Click
Dim myProcess As Process = _
System.Diagnostics.Process.Start("sample.txt")
myProcess.WaitForExit()
MessageBox.Show("Notepad was closed at: " & _
myProcess.ExitTime & "." & _
System.Environment.NewLine & "Exit Code: " & _
myProcess.ExitCode)
myProcess.Close()
End Sub
My next article will explain process implementation using .NET. Shown below is the screenshot of the sample utility.
Requirements
- Namespace:
System.Diagnostics
. - Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family.
- Assembly: System (in System.dll).
.NET Framework Security
SecurityPermission
for calling any members of System.Diagnostic.Process
with full trust. Associated enumeration: PermissionState.Unrestricted
.
Disclaimer
The opinions expressed in this paper are those of the author. These are not necessarily endorsed by the companies, and there is no implication that any of these ideas or concepts will be delivered as offerings or products by those companies.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.