在Windows上用C ++执行等效的“Kill Process Tree”

问题描述 投票:14回答:5

我们有一个C ++任务,它将分叉一个新进程。反过来,这个过程可能有几个子进程。如果任务超过规定的时间,我们将要杀死该分叉进程。

但是,我们不希望孤立它产生的进程。我们希望他们都死了。我使用了Process Explorer,它有一个“杀死进程树”选项,类似于Windows任务管理器的“结束进程树”,所以我猜/假设有一个公共API来执行此操作。有没有人这样做,或者知道对公共API的引用呢?

c++ windows kill
5个回答
20
投票

您可能想要考虑“Jobs API”。 CreateJobObject和朋友们。您可以通过设置适当的属性来强制子进程保留在作业中。然后你可以随时打电话给TerminateJobObject

澄清:这不是任务管理器所做的。


6
投票

我建议去工作对象路线,如上所述,它将是最可靠的。

如果你不能去工作对象路线,你可以使用toolhelp API来获取父进程ID并以这种方式构建树。但是要小心,因为Windows没有强大的父/子关系,并且PID可以被回收。您可以使用GetProcessTimes查询进程的创建时间,并检查它是否比子进程更早。如果树中的中间进程终止,您将无法进一步遍历树。

// Error handling removed for brevity
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 process;
ZeroMemory(&process, sizeof(process));
process.dwSize = sizeof(process);
Process32First(snapshot, &process);
do
{
    // process.th32ProcessId is the PID.
    // process.th32ParentProcessID is the parent PID.

} while (Process32Next(snapshot, &process));

5
投票

有一个名为TerminateProcess()的Win32函数。它应该为你做的工作。

或者,我发现taskkill命令对这样的事情很有用。

从命令行:

taskkill /F /T /IM program.exe

来自代码:

system("taskkill /F /T /IM program.exe");

其他开关(直接来自taskkill /?):

 TASKKILL [/S system [/U username [/P
 [password]]]]
          { [/FI filter] [/PID processid | /IM imagename] } [/F] [/T]

 Description:
     This command line tool can be used to end one or more processes.
     Processes can be killed by the process id or image name.

 Parameter List:
     /S    system           Specifies the remote system to connect to.

     /U    [domain\]user    Specifies the user context under which
                            the command should execute.

     /P    [password]       Specifies the password for the given
                            user context. Prompts for input if omitted.

     /F                     Specifies to forcefully terminate
                            process(es).

     /FI   filter           Displays a set of tasks that match a
                            given criteria specified by the filter.

     /PID  process id       Specifies the PID of the process that
                            has to be terminated.

     /IM   image name       Specifies the image name of the process
                            that has to be terminated. Wildcard '*'
                            can be used to specify all image names.

     /T                     Tree kill: terminates the specified process
                            and any child processes which were started by it.

     /?                     Displays this help/usage.

-约翰


1
投票

你想找到你要杀死的进程的进程ID,然后“走树”它的孩子(和他们的孩子,等等......),记下他们的pid,然后很好地快速杀死所有进程。


0
投票

您还可以使用WMI,路线规划,您可以创建一个类来执行任务。 这个"Where can I find the WMI documentation?"The WMI COM libraryWMI C++ Application Examples

© www.soinside.com 2019 - 2024. All rights reserved.