在.Net中,如何获得一个进程的父进程?
一个简单的方法:
var performanceCounter = new PerformanceCounter("Process", "Creating Process ID", "Child Process Name");
return Process.GetProcessById((int)performanceCounter.NextValue());
这个方法哪里都好,就是效率不好。创建PerformanceCounter的那句在我的PC要执行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