在.NET中,如何查找一个进程的父进程

最简单的方式:

var performanceCounter = new PerformanceCounter("Process", "Creating Process ID", "Child Process Name");

 

不过这种方式有个很严重的问题就是效率。在我的测试机上,创建PerformanceCounter的时间超过了1.5秒。如果效率对你很重要的话,你可以考虑PInvoke方式。

static Process GetParentProcess(Process childProcess)

{

   IntPtr toolhelp32SnapshotHandle = WindowsSdk.CreateToolhelp32Snapshot(WindowsSdk.TH32CS_SNAPPROCESS, 0);

 

   if (toolhelp32SnapshotHandle != IntPtr.Zero)

   {

      var processEntry32 = new Owl.WindowsSdk.PROCESSENTRY32();

      processEntry32.dwSize =

          (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Owl.WindowsSdk.PROCESSENTRY32));

 

      if (WindowsSdk.Process32First(toolhelp32SnapshotHandle, ref processEntry32))

      {

         int parentProcessId = 0;

         do

         {

            if (childProcess.Id == processEntry32.th32ProcessID)

            {

               parentProcessId = (int)processEntry32.th32ParentProcessID;

               break;

            }

         }

         while (parentProcessId == 0 && WindowsSdk.Process32Next(toolhelp32SnapshotHandle, ref processEntry32));

 

         if (parentProcessId > 0)

            return Process.GetProcessById(parentProcessId);

      }

   }

   return null;

}

 

#region Constant defination

internal static uint TH32CS_SNAPPROCESS = 2;

#endregion

 

#region Struct defination

[StructLayout(LayoutKind.Sequential)]

internal struct PROCESSENTRY32

{

   public uint dwSize;

   public uint cntUsage;

   public uint th32ProcessID;

   public IntPtr th32DefaultHeapID;

   public uint th32ModuleID;

   public uint cntThreads;

   public uint th32ParentProcessID;

   public int pcPriClassBase;

   public uint dwFlags;

   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]

   public string szExeFile;

};

#endregion

 

#region Kernel32 functions

[DllImport("kernel32.dll", SetLastError = true)]

internal static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);

 

[DllImport("kernel32.dll")]

internal static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

 

[DllImport("kernel32.dll")]

internal static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

#endregion

posted @ 2010-12-07 11:09  夜深沉  阅读(382)  评论(0)    收藏  举报