Skip to content

Instantly share code, notes, and snippets.

@wadewegner
Created January 7, 2015 21:26
Show Gist options
  • Save wadewegner/193b74a0facbaeefe59d to your computer and use it in GitHub Desktop.
Save wadewegner/193b74a0facbaeefe59d to your computer and use it in GitHub Desktop.
Attempt to kill the right w3wp processes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace GetParentProcess
{
class Program
{
static void Main(string[] args)
{
string process1Name = "cmd";
string process2Name = "w3wp";
var cmdProcesses = Process.GetProcessesByName(process1Name);
if (cmdProcesses.Length > 0)
{
foreach (var cmdProcess in cmdProcesses)
{
int cmdId = cmdProcess.Id;
Console.WriteLine("Found cmd.exe: " + cmdId);
int unknownId = Process.GetProcessById(cmdId).Parent().Id;
if (Process.GetProcessById(cmdId).Parent().ProcessName == process2Name)
{
int scmProcessId = unknownId;
Console.WriteLine("Found w3wp.exe id: " + scmProcessId);
var w3wpProcesses = Process.GetProcessesByName(process2Name);
if (w3wpProcesses.Length > 0)
{
foreach (var w3wpProcess in w3wpProcesses)
{
Console.WriteLine("Found w3wp.exe id: " + w3wpProcess.Id);
if (w3wpProcess.Id != scmProcessId)
{
Console.WriteLine("Killing w3wp.exe id: " + w3wpProcess.Id);
w3wpProcess.Kill();
}
}
}
}
}
}
}
}
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));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment