private static Process ParentProcess(this Process process)
{
if (OsUtils.IsUnixOs())
{
// TODO: find a way to implement this in mono on a mac/linux machine
return null;
}
var parentPid = 0;
var processPid = process.Id;
const uint TH32_CS_SNAPPROCESS = 2;
// Take snapshot of processes
var hSnapshot = CreateToolhelp32Snapshot(TH32_CS_SNAPPROCESS, 0);
if (hSnapshot == IntPtr.Zero)
{
return null;
}
var procInfo = new PROCESSENTRY32 {dwSize = (uint) Marshal.SizeOf(typeof (PROCESSENTRY32))};
// Read first
if (Process32First(hSnapshot, ref procInfo) == false)
{
return null;
}
// Loop through the snapshot
do
{
// If it's me, then ask for my parent.
if (processPid == procInfo.th32ProcessID)
{
parentPid = (int) procInfo.th32ParentProcessID;
}
} while (parentPid == 0 && Process32Next(hSnapshot, ref procInfo)); // Read next
if (parentPid <= 0)
{
return null;
}
try
{
return Process.GetProcessById(parentPid);
}
catch (ArgumentException)
{
//Process with an Id of X is not running
return null;
}
}