When starting a process in VB.Net, I would like to be able to identify it to later kill it and all its children if necessary.
I launch my process this way :
Dim mainProcessHandler As New ProcessStartInfo()
Dim mainProcess As Process
mainProcessHandler.FileName = "something_01out18.bat"
mainProcessHandler.Arguments = "-d"
mainProcessHandler.WindowStyle = ProcessWindowStyle.Hidden
mainProcess = Process.Start(mainProcessHandler)
If I do a
mainProcess .Kill()
it will close all cmd windows opened. But none of any other process that have been launched by the bat script.
I'm pretty sure that the OS give an ID to my process when I start it but I didn't succeed to get it. If that not the case, I didn't find either how to give a ID myself to the process.
At the end of the day, I would like to list all child processes, kill them, kill the father process but none of the other "cmd" process running on the PC.
Is there a way to do such things ?
Based on the C# code given as part of an answer to Find all child processes of my own .NET process, I used the following code that seem to work to kill all children of a process knowing its PID :
Sub killChildrenProcessesOf(ByVal parentProcessId As UInt32)
Dim searcher As New ManagementObjectSearcher(
"SELECT * " &
"FROM Win32_Process " &
"WHERE ParentProcessId=" & parentProcessId)
Dim Collection As ManagementObjectCollection
Collection = searcher.Get()
If (Collection.Count > 0) Then
consoleDisplay("Killing " & Collection.Count & " processes started by process with Id """ & parentProcessId & """.")
For Each item In Collection
Dim childProcessId As Int32
childProcessId = Convert.ToInt32(item("ProcessId"))
If Not (childProcessId = Process.GetCurrentProcess().Id) Then
killChildrenProcessesOf(childProcessId)
Dim childProcess As Process
childProcess = Process.GetProcessById(childProcessId)
consoleDisplay("Killing child process """ & childProcess.ProcessName & """ with Id """ & childProcessId & """.")
childProcess.Kill()
End If
Next
End If
End Sub
For information, it is needed to :
Imports System.Management
Then if you use Visual Studio, you'll need to go under the project menu, select "Add Reference...", under the ".Net" tab, scroll down to "System.Management" and select the line corresponding to "System.Management" and click OK. (as stated in this answer)
When correctly called, this Sub is satisfying to kill all children started by a parent process. If need, a basic parentProcess.kill kill the parent process.