【问题标题】:Identify a process started in VB.Net to be able to kill it and all its children later识别在 VB.Net 中启动的进程,以便以后能够杀死它及其所有子进程
【发布时间】:2018-09-04 11:07:53
【问题描述】:

当在 VB.Net 中启动一个进程时,我希望能够识别它,以便以后在必要时杀死它及其所有子进程。

我以这种方式启动我的流程:

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)

如果我这样做

mainProcess .Kill()

它将关闭所有打开的 cmd 窗口。但是 bat 脚本没有启动任何其他进程。

我很确定操作系统在我启动它时会为我的进程提供一个 ID,但我没有成功获取它。如果不是这样,我也没有找到如何自己为流程提供 ID。

最后,我想列出所有子进程,杀死它们,杀死父进程,但没有其他“cmd”进程在 PC 上运行。

有没有办法做这样的事情?

【问题讨论】:

标签: vb.net process pid kill


【解决方案1】:

根据作为Find all child processes of my own .NET process 答案的一部分给出的 C# 代码,我使用以下代码似乎可以杀死知道其 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

有关信息,需要:

Imports System.Management

然后,如果您使用 Visual Studio,则需要在项目菜单下选择“添加引用...”,在“.Net”选项卡下,向下滚动到“System.Management”并选择该行对应于“System.Management”,然后单击“确定”。 (如this answer中所述)

当正确调用时,这个 Sub 可以令人满意地杀死由父进程启动的所有子进程。如果需要,一个基本的 parentProcess.kill 杀死父进程。

【讨论】:

  • 最初提交的代码存在串联问题,导致其无法工作。这篇帖子就这样解决了。
  • 'Get' 不是 'ManagementObjectSearcher' 的成员?我收到此错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多