Process Extension: GetParentProcess
Microsoft suggests to use the performance counter to find the parent process.
I find this quite slow and failed to work when running as service (i had to call it before calling ServiceBase.Run), so i use the native Win32 approach.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System.Diagnostics
{
public static class ProcessExtension
{
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(SafeFileHandle hObject);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern SafeFileHandle CreateToolhelp32Snapshot(uint flags, uint processid);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool Process32Next(SafeFileHandle handle, ref ProcessEntry32 pe);
[StructLayout(LayoutKind.Sequential)]
private struct ProcessEntry32
{
public int dwSize;
public uint cntUsage;
public int th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public int th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string szExeFile;
};
public static Process GetParentProcess(this Process process)
{
Process retval = null;
int pid = process.Id;
SafeFileHandle snapShot = CreateToolhelp32Snapshot(0x2, 0);
try
{
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = 296; // Marshal.SizeOf(pe32);
while (Process32Next(snapShot, ref pe32))
{
if (pid == pe32.th32ProcessID)
{
retval = Process.GetProcessById(pe32.th32ParentProcessID);
break;
}
}
}
finally { CloseHandle(snapShot); }
return retval;
}
}
}
so I’m simply able to call
Process parentProcess = Process.GetCurrentProcess().GetParentProcess();
Advertisement
[...] by the Service Control Manager process (services.exe) or not and act the right way (Check my previous post about finding a process’ [...]
… at your Service (Part I) « programming with esskar
October 5, 2009 at 7:35 am