How to Get Parent Process in .Net in Managed Way

How to get parent process in .NET in managed way

This code provides a nice interface for finding the Parent process object and takes into account the possibility of multiple processes with the same name:

Usage:

Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id);

Code:

public static class ProcessExtensions {
private static string FindIndexedProcessName(int pid) {
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;

for (var index = 0; index < processesByName.Length; index++) {
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int) processId.NextValue() == pid) {
return processIndexdName;
}
}

return processIndexdName;
}

private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int) parentId.NextValue());
}

public static Process Parent(this Process process) {
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}

How can I get the PID of the parent process of my application

WMI is the easier way to do this in C#. The Win32_Process class has the ParentProcessId property. Here's an example:

using System;
using System.Management; // <=== Add Reference required!!
using System.Diagnostics;

class Program {
public static void Main() {
var myId = Process.GetCurrentProcess().Id;
var query = string.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);
var search = new ManagementObjectSearcher("root\\CIMV2", query);
var results = search.Get().GetEnumerator();
results.MoveNext();
var queryObj = results.Current;
var parentId = (uint)queryObj["ParentProcessId"];
var parent = Process.GetProcessById((int)parentId);
Console.WriteLine("I was started by {0}", parent.ProcessName);
Console.ReadLine();
}
}

Output when run from Visual Studio:

I was started by devenv

Getting parent process / Restarting a process C#

See
How to get parent process in .NET in managed way

Find out which process is responsible for starting the current one

A process can have a parent process id which you can query via WMI, for example, try:

wmic process get processid,parentprocessid

Process explorer also visualizes the processes in a tree like manner:
https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer

An SO about how to query the process ID, this particular answer is the WMI one. As stated in the answer, it could be quite slow. Using Pinvoke may gain some speed, but the code is not easy:

public static Process GetParent(this Process process)
{
try
{
using (var query = new ManagementObjectSearcher(
"SELECT * " +
"FROM Win32_Process " +
"WHERE ProcessId=" + process.Id))
{
return query
.Get()
.OfType<ManagementObject>()
.Select(p => Process.GetProcessById((int)(uint)p["ParentProcessId"]))
.FirstOrDefault();
}
}
catch
{
return null;
}
}

https://stackoverflow.com/a/46346244/4122889

You'll likely need this package but that depends on your framework version:
https://www.nuget.org/packages/System.Management/

Determining the parent process id from C#

WIN32_Process has processid and parent processid. Getting the WMI data on 64-bit is a bit more difficult, but still possible by changing the provider flags.

How To Get PPID

If you can use System.Management, it's easy enough:

    private static int GetParentProcess(int Id)
{
int parentPid = 0;
using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'"))
{
mo.Get();
parentPid = Convert.ToInt32(mo["ParentProcessId"]);
}
return parentPid;
}

Otherwise you may have to resort to P/Invoke calls via CreateToolhelp32Snapshot like this

Getting the name of what program ran an console app

You can get the parent process of some other process like this:

public static Process GetParentProcess(Process process)
{
string query = "SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = " + process.Id;
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(query))
{
foreach (ManagementObject mo in mos.Get())
{
if (mo["ParentProcessId"] != null)
{
try
{
var id = Convert.ToInt32(mo["ParentProcessId"]);
return Process.GetProcessById(id);
}
catch
{
}
}
}
}
return null;
}

Inside your console app you would use it like

var parent = GetParentProcess(Process.GetCurrentProcess());

From this you can get all information about parent process.

How to get parent process in .NET in managed way

This code provides a nice interface for finding the Parent process object and takes into account the possibility of multiple processes with the same name:

Usage:

Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id);

Code:

public static class ProcessExtensions {
private static string FindIndexedProcessName(int pid) {
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;

for (var index = 0; index < processesByName.Length; index++) {
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int) processId.NextValue() == pid) {
return processIndexdName;
}
}

return processIndexdName;
}

private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int) parentId.NextValue());
}

public static Process Parent(this Process process) {
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}

C#: How to find if process was invoked by current application?

Usage:

Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id);

Code:

public static class ProcessExtensions {
private static string FindIndexedProcessName(int pid) {
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;

for (var index = 0; index < processesByName.Length; index++) {
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int) processId.NextValue() == pid) {
return processIndexdName;
}
}

return processIndexdName;
}

private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int) parentId.NextValue());
}

public static Process Parent(this Process process) {
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}

Source: https://stackoverflow.com/a/2336322/706867



Related Topics



Leave a reply



Submit