/// <summary> /// For each process in the system, enumerates a tuple of parent-process-id,process-id. /// </summary> public static IEnumerable <(int parentProcessId, int processId)> ParentChildProcessIds() { var procEntry = new WinAPI.PROCESSENTRY32(); procEntry.dwSize = (uint)Marshal.SizeOf(typeof(WinAPI.PROCESSENTRY32)); var handleToSnapshot = WinAPI.CreateToolhelp32Snapshot((uint)WinAPI.SnapshotFlags.Process, 0); try { if (WinAPI.Process32First(handleToSnapshot, ref procEntry)) { do { yield return((int)procEntry.th32ParentProcessID, (int)procEntry.th32ProcessID); }while (WinAPI.Process32Next(handleToSnapshot, ref procEntry)); } else { throw new InternalErrorException("Process enumeration failed; win32 error code: {0}".Fmt(Marshal.GetLastWin32Error())); } } finally { WinAPI.CloseHandle(handleToSnapshot); } }
public static int GetParentProcessId(int id) { var pe32 = new WinAPI.PROCESSENTRY32 { dwSize = (uint)Marshal.SizeOf(typeof(WinAPI.PROCESSENTRY32)) }; using (var hSnapshot = WinAPI.CreateToolhelp32Snapshot(WinAPI.SnapshotFlags.Process, (uint)id)) { if (hSnapshot.IsInvalid) { throw new Win32Exception(); } if (!WinAPI.Process32First(hSnapshot, ref pe32)) { var errno = Marshal.GetLastWin32Error(); if (errno == WinAPI.ERROR_NO_MORE_FILES) { return(-1); } throw new Win32Exception(errno); } do { if (pe32.th32ProcessID == (uint)id) { return((int)pe32.th32ParentProcessID); } } while (WinAPI.Process32Next(hSnapshot, ref pe32)); } return(-1); }
/// <summary> /// For each process in the system, enumerates a tuple of parent-process-id,process-id. /// </summary> public static IEnumerable<Tuple<int, int>> ParentChildProcessIds() { WinAPI.PROCESSENTRY32 procEntry = new WinAPI.PROCESSENTRY32(); procEntry.dwSize = (uint) Marshal.SizeOf(typeof(WinAPI.PROCESSENTRY32)); IntPtr handleToSnapshot = WinAPI.CreateToolhelp32Snapshot((uint) WinAPI.SnapshotFlags.Process, 0); try { if (WinAPI.Process32First(handleToSnapshot, ref procEntry)) { do yield return Tuple.Create((int) procEntry.th32ParentProcessID, (int) procEntry.th32ProcessID); while (WinAPI.Process32Next(handleToSnapshot, ref procEntry)); } else { throw new RTException("Process enumeration failed; win32 error code: {0}".Fmt(Marshal.GetLastWin32Error())); } } finally { WinAPI.CloseHandle(handleToSnapshot); } }