Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force kill on process

Tags:

c#

I have this loop that runs continuously as a process to check if the mstsc.exe is running.

for (; ; )
{
    System.Diagnostics.Process[] pname = System.Diagnostics.Process.GetProcessesByName("mstsc");

    if (pname.Length != 0)
    {

    }
    else
    {
        System.Diagnostics.Process.Start(@"mstsc.exe");
    }
    System.Threading.Thread.Sleep(3000);
}

The problem is that on logoff, reboot, or shutdown I get this.

enter image description here

I tried to end the process on Form_Closing or with

Microsoft.Win32.SystemEvents.SessionEnded += 
  new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);

and I still get this...

How could I force this process to kill correctly?

like image 344
Drew Salesse Avatar asked Apr 30 '13 17:04

Drew Salesse


1 Answers

That happends when process has child processes. You have to kill whole process tree.

Kill process tree programmatically in C#

Code from link above (provided by Gravitas):

/// <summary>
/// Kill a process, and all of its children.
/// </summary>
/// <param name="pid">Process ID.</param>
private static void KillProcessAndChildren(int pid)
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
    ManagementObjectCollection moc = searcher.Get();
    foreach (ManagementObject mo in moc)
    {
        KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
    }
    try
    {
        Process proc = Process.GetProcessById(pid);
        proc.Kill();
    }
    catch (ArgumentException)
    {
        // Process already exited.
    }
}
like image 183
Kamil Avatar answered Sep 18 '22 01:09

Kamil