gpt4 book ai didi

vb.net - 在 vb.net 上停止完整的进程树

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:23:38 24 4
gpt4 key购买 nike

我编写了这个简单的算法来停止来自 vb.net 的完整进程树:

Private Sub TerminateProcessTree2(P As Process)
Dim Tree = GenerateProcessTree(P)
For Each childproc As Process In Tree
Try
If childproc.HasExited = False Then childproc.Kill()
Catch ex As Exception
AddError("Could not delete process " & childproc.ProcessName & ". " & ex.Message)
End Try
Next
Dim pName As String = "<unknown>"
Try
If P IsNot Nothing Then
pName = P.ProcessName
If P.HasExited = False Then P.Kill()
End If
Catch ex As Exception
AddError("Error killing process " & pName & ". " & ex.Message)
End Try

End Sub

Function GenerateProcessTree(p As Process) As Collections.Generic.HashSet(Of Process)
Dim hash As New Collections.Generic.HashSet(Of Process)
GenerateProcessTreeNode(p, hash)
Return hash
End Function

Private Sub GenerateProcessTreeNode(parent As Process, hash As Collections.Generic.HashSet(Of Process))
Dim searcher As New ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" & parent.Id)
Dim moc As ManagementObjectCollection = searcher.[Get]()
For Each mo As ManagementObject In moc
Dim i As Integer = CInt(mo("ProcessID"))
Dim childP As Process
Try
childP = Process.GetProcessById(i)
If childP IsNot Nothing AndAlso hash.Contains(childP) = False Then
hash.Add(childP)
GenerateProcessTreeNode(childP, hash)
End If
Catch ex As Exception
AddError("Could not get process ID for " & mo.ToString)
Continue For
End Try
Next
End Sub

但是,我的一些程序用户告诉我,每隔一段时间(比如百分之一或百分之二的次数),该算法会关闭所有进程,而不仅仅是给定进程的子进程。这怎么可能?算法有什么需要修正的吗?我想有最简单的方法可以做到这一点,但我想知道为什么这个方法失败了。

最佳答案

您的代码按预期工作并且是正确的。 IMO 问题的发生是因为 WMI property ParentProcessId . MSDN 说:

ParentProcessId

Data type: uint32
Access type: Read-only

Unique identifier of the process that creates a process.
Process identifier numbers are reused, so they only identify
a process for the lifetime of that process. It is possible that
the process identified by ParentProcessId is terminated, so
ParentProcessId may not refer to a running process. It is also
possible that ParentProcessId incorrectly refers to a process
that reuses a process identifier. You can use the CreationDate
property to determine whether the specified parent was created
after the process represented by this Win32_Process instance
was created.

我假设,您的 HashSet holds 在某个时候 ProcessId 被系统用新进程和新进程替换,而不是子进程不再存在,但仍在集合中,并在从列表中获取时终止。

您可以广泛记录 process.Kill() 的每次调用(名称、进程 ID、时间戳等),然后尝试使用日志跟踪问题。

关于vb.net - 在 vb.net 上停止完整的进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23185763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com