Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Architecture
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
Bing
BizTalk
Book Excerpts
Build and Deploy
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Design Patterns
Development Process
Display Technologies
Distributed Computing
DotNetNuke
DSL
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
Internet Explorer 8.0
Interviews
iPhone
Iron Ruby
Java
Java Script
jQuery
LINQ
Linux
Mac OS X
MDX
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
Network
NHibernate
Object Oriented Development
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
Podcasts
Post Mortem
PowerPoint
Print/Output
Product News
Product Reviews
Project Management
Python
Q&A
Rails
Rake
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Search
Security
Services
SharePoint
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server CE/AnyWhere/Mobile/Compact
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
Tips
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WF
Whitepapers
Windows 7
Windows Azure
Windows Live
Windows Server
Windows Vista
WinForms
Workflow
WPF
XAML
XML
XNA
XSLT



DevConnections


 


DevReach

Reader rating:
Click here to read 16 comments about this article.
Article source: CoDe (2004 - March/April)


Article Pages:  1  2 3 4 5 - Next >


Managing Processes in .NET

The Process class allows you to gain full control over system processes.You can start and stop processes and retrieve information about running processes such as the list of loaded modules and the characteristics of the memory occupied. The class also features handy methods to know whether a process is responding or has just exited and with which return code. Programmers also have full control over the style of the window the process runs in. After an overview of the capabilities of the Process class, this article demonstrates how to hide running console processes, monitor their execution, and capture any output. I'll use this strategy to create a sample Compression class to use with WinZip and gzip (popular tools for compressing data).

Have you ever wanted to manage processes in Win32 code? When it comes to this, there's good and bad news. On the good news side, you can do virtually everything you desire, including block your current process waiting for another process to terminate. On the bad news side, you must work with an API that is not one for the faint-hearted. CreateProcess is the one-size-fits-all function that creates a new Win32 process and manages impersonation and security settings. This function has quite a quirky syntax. The Win32 SDK supplies several functions including CreateProcess and OpenProcess that provide the core functionalities. The Win32 SDK provides ToolHelp API, a secondary SDK, but it is not available on all possible combinations of Win32 operating systems. ToolHelp API offers more advanced functions including the capability to list modules and dependencies, capture the memory footprint, and ping process.

"
The Process class provides access to local and remote processes and enables you to start and stop processes on the local machine. The class represents a superset of the capabilities of the CreateProcess Win32 API.
"

Nicely enough, .NET groups all these platform services under a single class?the Process class. Whatever you need to do that involves spawning a new process or controlling a running one, you can do from this unique (and rather powerful) entry point.

The Process Class

The Process class provides access to local and remote processes and enables you to start and stop processes on the local machine. The class represents a superset of the capabilities of the CreateProcess Win32 API. In addition, the Process class makes working with running instances of applications particularly easy. For example, you only need a single line of code to start a new process from within a .NET application:

Process.Start("Notepad.exe")

If you need to open a particular document, say, a Word document, it's even easier.

Process.Start("invoice.doc")

In this case, the Process class is smart enough to figure out that the argument is not an executable. It looks up the system registry for a match on the extension (.doc in this case), gets the executable associated with that type of file, and starts it up. This behavior reveals another powerful Win32 API function working under the hood?ShellExecuteEx, which is designed to open a document?be it an executable (that is, an .exe or .bat file), or a document file associated with a program (such as a .txt or a .doc file).

The Process class has both instance and shared (static, if you speak C#) methods. Table 1 lists all the methods exposed by the class. Looking at the table will give you a clear idea of the class' capabilities.

You have two ways to terminate a process?Kill and CloseMainWindow. The former stops execution immediately, whereas the latter simply posts a termination message to the message queue. The Kill method can cause loss of data if it reaches the process at a critical stage. You must use the Kill method if you have to programmatically terminate a program that doesn't have a graphical user interface (such as a console program or a system service). You should always use CloseMainWindow to stop GUI programs.

You may have a programming situation in which you need to spawn an external program and wait for it to terminate. By default, a spawned process runs independently from the parent. To synchronize the two so that the parent resumes when the child has completed, you use the WaitForExit method. WaitForExit is an instance-based method that requires a fresh instance of the Process class to work.

Dim p As New Process
p = Process.Start("notepad.exe")
p.WaitForExit()

The Start method has several overloads; some shared and one instance-based. The instance-based overload doesn't accept parameters. To specify the name of the executable to run, you need to instantiate and fill a class named ProcessStartInfo. Let's discover more about this class and process information in general.

&

By: Leonardo Esposito

dinoesp@hotmail.com

Dino Esposito is a mentor at Solid Quality Mentors where he manages the ASP.NET, workflow, and AJAX courseware. A speaker at many industry events including Microsoft TechEd, Basta, DevWeek, and DevConnections, Dino is the author of the two volumes of Programming Microsoft ASP.NET 2.0 Applications, for Microsoft Press. You can find late breaking news at http://weblogs.asp.net/despos.

leesposi@libero.it

Fast Facts

If you need to launch programs from within a .NET application, the Process class is the right tool. It not only allows you to start and stop a process, but it also provides detailed information about running processes. Using the Process class you can easily access the modules and memory footprint of each process so that you can emulate the Windows Tasks Manager. Furthermore, the process startup information you're allowed to specify provides fertile ground so you can implement advanced functions such as capturing the output of a console program and wrapping a console program into a set of .NET classes.



MethodDescription
CloseCloses the process and frees all the resources associated with the instance.
CloseMainWindowSends a WM_CLOSE message to the main window of the process. Makes sense only if the process has a user interface.
EnterDebugModeShared method, enables the SeDebugPrivilege privilege on the current thread, meaning that the current process can operate as a debugger.
GetCurrentProcessShared method, returns a new instance of the Process class associated with the currently active process.
GetProcessByIdShared method, returns a new instance of the Process class associated with the process matching the specified ID and machine name.
GetProcessesShared method, returns an array of Process objects each associated with a currently active process.
GetProcessesByNameShared method, returns an array of Process objects each associated with a currently active process with the specified name (for example, all instances of Notepad).
KillImmediately terminates the associated process.
LeaveDebugModeShared method, revokes the privilege that enables the current process to operate as a debugger.
RefreshDiscards any cached information about the process and resets the associated Process object.
StartShared method, starts a process and returns the associated Process object. This method also has an instance-based version.
WaitForExitStops the current process until the associated process exits or for the specified duration.
WaitForInputIdleCauses the current process to wait for the associated process to enter an idle state.


Article Pages:  1  2 3 4 5 - Next Page: 'Discover Process Information' >>

Page 1: Managing Processes in .NET
Page 2: Discover Process Information
Page 3: Specify Startup Information
Page 4: Capturing Process Output
Page 5: Wrapping Zip Functionalities

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
4.0 out of 5

81 people have rated this article.

      Hacker Halted

 

DevLink