我们有一个C ++任务,它将分叉一个新进程。反过来,这个过程可能有几个子进程。如果任务超过规定的时间,我们将要杀死该分叉的进程。
但是,我们不希望孤立它产生的进程。我们希望他们都死了。我使用了Process Explorer,它有一个“杀死进程树”选项,类似于Windows任务管理器的“结束进程树”,所以我猜/假设有一个公共API来执行此操作。有没有人这样做过,或者知道对公共API的引用呢?
答案 0 :(得分:20)
您可能想要考虑“Jobs API”。 CreateJobObject
和朋友们。您可以通过设置适当的属性来强制子进程保留在作业中。然后,您可以随时拨打TerminateJobObject
。
澄清:这不是任务管理器所做的。
答案 1 :(得分: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));
答案 2 :(得分: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.
-John
答案 3 :(得分:1)
你想要找到你要杀死的进程的进程ID,然后找到它的子进程(及其子进程等等),记下它们的pid,然后终止所有进程很快很快。
答案 4 :(得分:0)
您还可以使用WMI,路线规划,您可以创建一个类来执行任务
请"Where can I find the WMI documentation?"
和The WMI COM library
和WMI C++ Application Examples