Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My winform application is launched by another application (the parent), I need determine the pid of the application which launch my application using C#.

like image 681
Salvador Avatar asked Mar 28 '10 03:03

Salvador


People also ask

What is a parent PID?

3. Parent Process ID Spoofing. Parent PID Spoofing is a technique that allows attackers to run processes under any parent process they want.

How do I find the PID of an application in Linux?

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

Is PID 0 for parent or child?

The line PID = fork(); returns the value of the fork() system call. The if (PID == 0) evaluates the return value. If PID is equal to zero then printf() is executed in the child process, but not in the parent process.


1 Answers

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

like image 156
Hans Passant Avatar answered Sep 25 '22 15:09

Hans Passant