在 Windows 上用 C++ 执行等效的“杀死进程树”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/604522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:05:48  来源:igfitidea点击:

Performing equivalent of "Kill Process Tree" in C++ on windows

c++windowskill

提问by Brett McCann

We have a C++ task that will fork a new process. That process in turn may have several child processes. If the task runs past an allotted time, we will want to kill that forked process.

我们有一个 C++ 任务将派生一个新进程。该进程又可能有多个子进程。如果任务运行超过分配的时间,我们将想要终止该分叉进程。

However, we don't want to orphan the processes it has spawned. We want them all to die. I have used Process Explorer and it has a "Kill Process Tree" option, similar to Windows Task Manager's "End Process Tree", so I'm guessing/assuming there is a public API to do this. Has anyone done this, or know of a reference to a public API that does?

但是,我们不想孤立它产生的进程。我们希望他们都死。我使用过进程资源管理器,它有一个“终止进程树”选项,类似于 Windows 任务管理器的“结束进程树”,所以我猜测/假设有一个公共 API 来做到这一点。有没有人这样做过,或者知道对公共 API 的引用?

回答by EFraim

You might want to consider the "Jobs API". CreateJobObjectand friends. You can enforce children processes to stay within the Job, by setting appropriate attribute. Then you can call TerminateJobObjectwhenever you want.

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

Clarification: this is NOT what Task Manager does.

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

回答by Michael

I suggest going the job object route, as indicated above, it will be the most reliable.

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

If you can't go the job object route, you can use the toolhelp API to get parent process ID's and build the tree that way. Be cautious though, since Windows doesn't have a strong parent/child relationship and it is possible for PID's to get recycled. You can use GetProcessTimesto query the creation time of the process, and check that it is older than the child. If an intermediate process in the tree is terminated, you will not be able to walk the tree further.

如果您不能走作业对象路线,您可以使用 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));

回答by John T

There is a Win32 function called TerminateProcess(). It should do the job for you.

有一个名为TerminateProcess()的 Win32 函数。它应该为您完成这项工作。

Alternatively, I've found the taskkill command to be useful for things like this.

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

from the command line:

从命令行:

taskkill /F /T /IM program.exe

from code:

来自代码:

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

other switches (straight from taskkill /? ):

其他开关(直接来自 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.

-John

-约翰

回答by James Caccese

You want to find the process id for the process you want to kill, then "walk the tree" of its children (and their children, and so on...), note their pids, and then kill all the processes nice and quickly.

您想找到要杀死的进程的进程 ID,然后“遍历”其子进程(以及它们的子进程,等等...)的进程 ID,记下它们的 pid,然后快速快速地杀死所有进程.

回答by lsalamon

You can also use WMI, route planning you can create a class to perform the tasks.
Se this "Where can I find the WMI documentation?"
and The WMI COM library
and WMI C++ Application Examples

您还可以使用 WMI,您可以创建路线规划类来执行任务。
参阅“我在哪里可以找到 WMI 文档?”
WMI COM 库
WMI C++ 应用程序示例