Skip to content
Advertisement

How to close all child processes in C#

C# code:

ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.Verb = "runas";        
processStartInfo.FileName = fileNameToExecute;
processStartInfo.Arguments = parameters;
Process process = new Process();
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
process.Close();

I am calling a java.exe from C# windows application. java.exe is used to test some websites. Java using Selenium to test the webpages by opening default web browser. It will open 3 to 10 times browsers and test the test cases. I want to add stop button in C# application and when we click it then it should close java.exe as well as those opened browsers. How to do it?

I tried to get process names by using exe name like this

Process[] processName = Process.GetProcessesByName(fileName.Substring(0, fileName.LastIndexOf('.')));

But it is not working.

Advertisement

Answer

Process process = new Process();
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;

process.StartInfo = processStartInfo;
process.Start();
javaExeProcessId = process.Id; //global variable
process.WaitForExit();
process.Close();

Before starting a new process I have stored the processId in a global variable.

private static void KillProcessAndChildren(int pid)
{
    // Cannot close 'system idle process'.
    if (pid == 0)
    {
        return;
    }
    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 (Exception ex)
    {
        // Process already exited.
    }
}


I called KillProcessAndChildren(javaExeProcessId); to kill the current process and its child processes wherever required.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement