/// <summary> /// Kills all child processes of the specified process. /// </summary> /// <param name="ProcessId">Process id</param> public static void KillAllDescendants(Process ProcessToKill) { bool bKilledAChild; do { bKilledAChild = false; // For some reason Process.GetProcesses() sometimes returns the same process twice // So keep track of all processes we already tried to kill var KilledPids = new HashSet <int>(); var AllProcs = Process.GetProcesses(); foreach (Process KillCandidate in AllProcs) { var VisitedPids = new HashSet <int>(); if (ProcessManager.CanBeKilled(KillCandidate.ProcessName) && !KilledPids.Contains(KillCandidate.Id) && IsOurDescendant(ProcessToKill, KillCandidate.Id, VisitedPids)) { KilledPids.Add(KillCandidate.Id); CommandUtils.Log("Trying to kill descendant pid={0}, name={1}", KillCandidate.Id, KillCandidate.ProcessName); try { KillCandidate.Kill(); bKilledAChild = true; } catch (Exception Ex) { CommandUtils.Log(TraceEventType.Warning, "Failed to kill descendant:"); CommandUtils.Log(TraceEventType.Warning, Ex); } break; // exit the loop as who knows what else died, so let's get processes anew } } } while (bKilledAChild); }
/// <summary> /// returns true if this process has any descendants /// </summary> /// <param name="ProcessToCheck">Process to check</param> public static bool HasAnyDescendants(Process ProcessToCheck) { Process[] AllProcs = Process.GetProcesses(); foreach (Process KillCandidate in AllProcs) { // Silently skip InvalidOperationExceptions here, because it depends on the process still running. It may have terminated. string ProcessName; try { ProcessName = KillCandidate.ProcessName; } catch (InvalidOperationException) { continue; } // Check if it's still running HashSet <int> VisitedPids = new HashSet <int>(); if (ProcessManager.CanBeKilled(ProcessName) && IsOurDescendant(ProcessToCheck, KillCandidate.Id, VisitedPids)) { CommandUtils.LogLog("Descendant pid={0}, name={1}", KillCandidate.Id, ProcessName); return(true); } } return(false); }
/// <summary> /// returns true if this process has any descendants /// </summary> /// <param name="ProcessToCheck">Process to check</param> public static bool HasAnyDescendants(Process ProcessToCheck) { Process[] AllProcs = Process.GetProcesses(); foreach (Process KillCandidate in AllProcs) { HashSet <int> VisitedPids = new HashSet <int>(); if (ProcessManager.CanBeKilled(KillCandidate.ProcessName) && IsOurDescendant(ProcessToCheck, KillCandidate.Id, VisitedPids)) { CommandUtils.Log("Descendant pid={0}, name={1}, filename={2}", KillCandidate.Id, KillCandidate.ProcessName, KillCandidate.MainModule != null ? KillCandidate.MainModule.FileName : "unknown"); return(true); } } return(false); }