Getting Parent Process ID from Child without passing any arguments


In C#, Parent runs ProcessChild through System.Diagonastics.Process and ProcessChild has following codes to find its Parent process Id without use of any arguments.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;
using System.Diagnostics;
namespace ProcessChild
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetParentProcess().Id);
Console.Read();
}

private static Process GetParentProcess()
{
int iParentPid = 0;
int iCurrentPid = Process.GetCurrentProcess().Id;

IntPtr oHnd = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

if (oHnd == IntPtr.Zero)
return null;

PROCESSENTRY32 oProcInfo = new PROCESSENTRY32();

oProcInfo.dwSize =
(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(PROCESSENTRY32));

if (Process32First(oHnd, ref oProcInfo) == false)
return null;

do
{
if (iCurrentPid == oProcInfo.th32ProcessID)
iParentPid = (int)oProcInfo.th32ParentProcessID;
}
while (iParentPid == 0 && Process32Next(oHnd, ref oProcInfo));

if (iParentPid > 0)
return Process.GetProcessById(iParentPid);
else
return null;
}

static uint TH32CS_SNAPPROCESS = 2;

[StructLayout(LayoutKind.Sequential)]
public struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
};

[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);

[DllImport("kernel32.dll")]
static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

[DllImport("kernel32.dll")]
static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
 }
}

Advertisements

One thought on “Getting Parent Process ID from Child without passing any arguments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s