Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Managing Processes and Shell API Functionality using .NET, Part 1

0.00/5 (No votes)
2 Mar 2006 1  
This article explains how the Windows OS handles processes, methods, and definitions.

Overview

This article discusses the following:

  • Background on processes
  • How Windows handles processes
  • Processclass operations
  • System.Diagnosticsclass

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.Diagnosticsnamespace. 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 Processclass, and get memory and thread information about running processes.

Contents

Introduction

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 Processclass 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 Processclass, 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 Processclass 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.Diagnosticsnamespace and the Processclass 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

Process Counter Column Headings

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

Processes versus Threads

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.

How to use the Process class in .NET?

A Look at the Process Class

The Processclass 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 Processclass are listed in Table 5.

In order to get detailed knowledge about process threads and modules, you need to use the ProcessThreadand ProcessModuleclasses.

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 ProcessThreadand ProcessModuleclasses.

The ProcessStartInfoclass 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 Processclass 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
"vb-comment">'[Visual Basic]
"vb-keyword">Public "vb-keyword">Class Process
       "vb-keyword">Inherits Component
"cs-comment">//[C#]
"cs-keyword">public "cs-keyword">class Process : Component
"cpp-comment">//[C++]
"cpp-keyword">public "cpp-keyword">__gc "cpp-keyword">class Process : "cpp-keyword">public Component
"cpp-comment">//[JScript]
public "cpp-keyword">class Process extends Component

System.Diagnostic.Process class

The System.Diagnostic.Processclass allows you to gain access to information regarding a process, and manage various operations of a process. The System.Diagnosticsnamespace allows you to interact with system processes, event logs, and performance counters. The Processclass allows the following operations:

  • Starting of processes
  • Stopping of processes
  • Controlling applications
  • Monitoring applications

Figure 6: System.DiagnosticClass

The System.Diagnostic.Processclass 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 BasePriorityfunction of the process allows you get the base priority of the associated process, which is already described above. The Handleproperty 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()/td>
PID (Process Identifier) ID/td>
User Name Get from StartInfo()/td>
Session ID Get from StartInfo()/td>
CPU Time TotalProcessorTime()/td>
Peak Memory Usage PeakPagedMemorySize()/td>
Base Priorities PriorityClass()/td>
Handles HandleCount()/td>
Threads Threads()/td>
I/O Reads

StandardInput()/p>

StandardOutput()/p>

StandardError()/p>

I/O Writes
I/O Other
I/O Read Bytes
I/O Write Bytes
I/O Other Bytes
Base Priority BasePriority()/td>
Paged Pool PagedMemorySize()/td>
NP Pool NonpagedSystemMemorySize()/td>
Virtual Memory Size VirtualMemorySize()/td>

Table 6. Windows process attributes in .NET

Process Component

A Processcomponent allows you to obtain a list of local, network, or system processes running on your computer. The Processcomponent 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 Processfor 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. Processcomponent attributes

Note: Each attributes of the Processcomponent is self-explanatory. There is no need to explain each of them separately.

Some of the important properties of the Processcomponent 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 Handleproperty of the Processcomponent helps to identify a resource. The ExitCodemethod 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 ExitTimemethod 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 GetProcessesmethod retrieves an array of Processclass 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 Processobject. Here are just a few of them.

VB.NET
"vb-keyword">Imports System.Diagnostics
"vb-keyword">Public "vb-keyword">Class getProcesses
   "vb-keyword">Dim clsProcess() "vb-keyword">As Process = _
       System.Diagnostics.Process.GetProcesses()
   updateListView()
   "vb-keyword">For intLength "vb-keyword">As Int16 = "vb-literal">0 "vb-keyword">To clsProcess.Length - "vb-literal">1
       "vb-keyword">Dim objitem "vb-keyword">As "vb-keyword">New ListViewItem(clsProcess(intLength).Id, "vb-literal">0)
       "vb-comment">' Place a check mark next to the item.
       "vb-comment">'item1.Checked = True
       objitem.SubItems.Add(clsProcess(intLength).ProcessName)
       objitem.SubItems.Add(clsProcess(intLength).BasePriority)
       lvwProcInfo.Items.Insert(intLength, objitem)
   "vb-keyword">Next
"vb-keyword">End Process
C#
Using System.Diagnostics;
System.Diagnostics.Process[] clsProcess = 
        System.Diagnostics.Process.GetProcesses();

ProcessStartInfo() Method

The ProcessStartInfoclass 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#
"cs-keyword">using System.Diagnostics;

"cs-keyword">namespace MyProcessSample
{
     "cs-comment">/// <summary>
     "cs-comment">/// Example of ProcessStartInfo() Method.
     "cs-comment">/// </summary>

    "cs-keyword">public "cs-keyword">class WordAutoPrint
    {
        "cs-keyword">public "cs-keyword">void PrintDoc()
        {

            Process myProcess = "cs-keyword">new Process();    
            myProcess.StartInfo.FileName = 
                     myDocumentsPath + "cpp-string">"\\MyFile.doc"; 
            myProcess.StartInfo.Verb = "cpp-string">"Print";
            myProcess.StartInfo.CreateNoWindow = "cs-keyword">true;
            myProcess.Start();
        }
    }
}

GetCurrentProcess(), GetProcessById(), GetProccessesByName(), and GetProcesses() Methods

The GetCurrentProcessmethod 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 GetProcessesByNameand GetProcessByIDmethods. 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 GetProcessNamewill 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 GetProcessByIDgets 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
"vb-keyword">Dim p1 "vb-keyword">As System.Diagnostics.Process _
    = System.Diagnostics.Process.GetCurrentProcess()
"vb-keyword">Dim p2 "vb-keyword">As System.Diagnostics.Process() = _
    System.Diagnostics.Process.GetProcessesByName("vb-string">"NOTEPAD")
"vb-keyword">Dim p3 "vb-keyword">As System.Diagnostics.Process = _
    System.Diagnostics.Process.GetProcessById("vb-literal">15)
C#
"cs-keyword">using System;
"cs-keyword">using System.Diagnostics;

"cs-comment">// Get the current process.
Process currentProcess = Process.GetCurrentProcess();
"cs-comment">// Get all instances of Notepad running on the local
"cs-comment">// computer.
Process [] localByName = Process.GetProcessesByName("cpp-string">"notepad");

"cs-comment">// Get a process on the local computer, using the process id.
Process localById = Process.GetProcessById("cs-literal">1234);

WaitForExit Method

The WaitForExitmethod 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.

"vb-keyword">Private "vb-keyword">Sub btnWaitForExit_Click( _
  "vb-keyword">ByVal sender "vb-keyword">As System."vb-keyword">Object, _
  "vb-keyword">ByVal e "vb-keyword">As System.EventArgs) _
  "vb-keyword">Handles btnWaitForExit.Click

  "vb-comment">' create a new process
  "vb-keyword">Dim myProcess "vb-keyword">As Process = _
     System.Diagnostics.Process.Start("vb-string">"sample.txt")

  "vb-comment">' wait until it exits
  myProcess.WaitForExit()

  "vb-comment">' display results
  MessageBox.Show("vb-string">"Notepad was closed at: " & _
     myProcess.ExitTime & "vb-string">"." & _
     System.Environment.NewLine & "vb-string">"Exit Code: " & _
     myProcess.ExitCode)
  myProcess.Close()
"vb-keyword">End "vb-keyword">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

SecurityPermissionfor calling any members of System.Diagnostic.Processwith 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here