How to Get the Pid of the Parent Process of My Application

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

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));
}
}

Getting the parent id of a given process in Ruby

You can just remember it in a variable:

parent_pid = Process.pid

Process.fork do
child_pid = Process.pid
puts parent_pid, child_pid
# do stuff
exit
end

Process.wait

# 94791
# 94798

alternatively, if you need the information on the level of the parent process:

parent_pid = Process.pid

child_pid = Process.fork do
# do stuff
exit
end

Process.wait
puts parent_pid, child_pid

# 6361
# 6362

Fetching parent process Id from child process

You should use the Native API and GetProcAddress to find the address of NtQueryInformationProcess.

typedef struct _PROCESS_BASIC_INFORMATION
{
NTSTATUS ExitStatus;
PPEB PebBaseAddress;
ULONG_PTR AffinityMask;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;

NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationProcess(
__in HANDLE ProcessHandle,
__in PROCESS_INFORMATION_CLASS ProcessInformationClass,
__out_bcount(ProcessInformationLength) PVOID ProcessInformation,
__in ULONG ProcessInformationLength,
__out_opt PULONG ReturnLength
);

PROCESS_BASIC_INFORMATION basicInfo;

NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &basicInfo, sizeof(basicInfo), NULL);
// My parent PID (*) is in basicInfo.InheritedFromUniqueProcessId

To get the grandparent PID, open the parent process using the parent PID and call NtQueryInformationProcess again on the parent process.

Note * - Strictly speaking, the parent process (the process which created the child process) is not actually recorded. InheritedFromUniqueProcessId just gives you the process from which attributes were inherited. But this is very rarely a problem.

Alternatively, if you don't like the Native API, use CreateToolhelp32Snapshot with TH32CS_SNAPPROCESS, which gives you the required information, except that you'll have to search through the list.

How can a Win32 process get the pid of its parent?

Notice that if the parent process terminates it is very possible and even likely that the PID will be reused for another process. This is standard windows operation.

So to be sure, once you receive the id of the parent and are sure it is really your parent you should open a handle to it and use that.

Getting the id of a Parent Process from its child in C

As Haris mentioned in his answer, You should use getppid() to get the pid of the parent.


In response to your comment here,

well i tried it , and lol that might seems funny , but my program killed my os , my linux machine shuted down

Let's have a look at your code,

else if (pid==0){ //child
sleep(5);
printf("%s","I am ready to murder my parent!");
kill(//parent id here,SIGINT);
printf("%s","I am an orphan now");
}
else{ // parent
printf("%s\n","I am the parent");
}

What will the parent process do after it finishes executing printf("%s\n","I am the parent"); ? It terminates.

So, who is the parent of a process whose original parent has terminated ? The child process becomes an orphan. Quoting from Wikipedia

An orphan process is a computer process whose parent process has finished or terminated, though it remains running itself. In a Unix-like operating system any orphaned process will be immediately adopted by the special init system process.

Therefore, when you are invoking kill() you are doing so on the init process. This is the reason for lol that might seems funny , but my program killed my os , my linux machine shuted down

Do have a look at this answer.

Finding parent process ID on Windows


C:\> wmic process get processid,parentprocessid,executablepath|find "process id goes here"

Windows Ruby get PID from process name

The sys-proctable gem can do that, here is a minimal example for getting the PID of the ruby.exe process on the system:

require 'sys/proctable'

def get_process_id(name)
Sys::ProcTable.ps.detect{|p| p.name == name}&.pid
end

puts get_process_id("ruby.exe")

That doesn't guarantee you will find the parent process tho, you will instead get the process with the lowest PID.

To actually find the "root process", you need to further select processes by checking if their parent process is either non-existent or a different process:

require 'sys/proctable'

def get_parent_process_id(name)
# generate a hash mapping pid -> process info
processes = Sys::ProcTable.ps.map{|p| [p.pid, p]}.to_h

# find the first matching process that has either no parent or a parent
# that doesn't match the process name we're looking for
processes.values.each do |p|
next if p.name != name

if processes[p.ppid].nil? || processes[p.ppid].name != name
return p.pid
end
end

nil
end

puts get_parent_process_id("chrome.exe")


Related Topics



Leave a reply



Submit