Inside and Out…

An attempt to understand technology better…

Enumerating Managed Processes

Posted by Gaurav Khanna on August 16, 2005

System.Diagnostics.Process class is a managed wrap over a subset of the ToolHelp API – as it enumerates only the process list. Not only that, it will list all the running processes, irrespective of whether they are running unmanaged code or running managed code. What if you wish to identify which of these processes are running managed code?

Unfortunately, neither the ToolHelp API, nor the Process class allow us to identify managed processes from the list they provide us. However, if you have noticed while debugging using Visual Studio, the debugger does identify a managed process in such a list:

VS debugger showing processes running managed code

So, how does the VS debugger do it?

Well, the CLR exposes debugging interfaces, which contain this functionality. These interfaces include ICorPublish, ICorPublishProcess, ICorPublishAppDomain, just to name a few. Infact, if you have installed the .NET Framework 2.0 SDK and navigate to the %SDKRoot%\v2.0\include folder, you will see the relevant header files that contain these interface definitions

The same identification can now also be done using managed code. Under %SDKRoot%\v2.0\bin folder, you will find, amongst others, MdbgCore.dll – the core of the managed debugger. If you ILASM this file (yes, its an assembly), you will see the managed wraps of the unmanaged interfaces mentioned above:

Managed wraps of the unmanaged interfaces

The starting point is Microsoft.Samples.Debugging.CorPublish.CorPublish. This lets us enumerate the managed processes, returning an instance of Microsoft.Samples.Debugging.CorPublish.CorPublishProcess type. Below is a sample that exemplifies doing the same:

using
System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Samples.Debugging.MdbgEngine;
using Microsoft.Samples.Debugging.CorPublish; namespace ManagedProcessList
{
    class Program
    {
        static void Main(string[] args)
        {
            CorPublish pub = new CorPublish();
            foreach (CorPublishProcess proc in pub.EnumProcesses())
            {
                Console.WriteLine(“{0} IsManaged: {1}”, proc.DisplayName, proc.IsManaged.ToString());
            }
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: