终止子进程时终止所有(grand)子进程 [英] Terminate all (grand)children when terminating a child process

查看:267
本文介绍了终止子进程时终止所有(grand)子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会跳进来,简要说明:



C ++,Windows API



使用 CreateProcess 创建子进程以运行外部(命令行)应用程序。我已经建立了一个超时,如果子进程在那时没有返回正常执行,我希望强制终止该子进程。



理想情况下,我希望该子进程的行为与调用 ExitProcess 相同,如果一个 Ctrl + C 发送到它的控制台(它从默认控制台控制处理程序调用 ExitProcess )。 p>

到目前为止,我的解决方案是使用 TerminateProcess 强制杀死孩子。这会迫使孩子立即终止,但不幸的是,如果那个孩子产生了自己的孩子,他们就会一直等到他们自然完成。



方法来告诉子进程调用 ExitProcess ,或强制所有子进程的子进程也终止 TerminateProcess 调用?



这些外部应用程序超出了我的控制范围,因此我无法修改它们以提供自定义的解决方案。



假设不知道子进程(名称/ pids /等),这将允许我手动调用 TerminateProcess 个别的子进程。虽然这可以通过手动枚举所有进程,映射进程关系和跟踪所有进程来完成,但我不认为这是一个有效的解决方案,除非是最后的手段。



谢谢您的时间。

解决方案

您可以使用作业对象,以将所有进程作为一个单元。您可以通过 CreateJobObject API创建作业对象,并分配一个进程到 AssignProcessToJobObject 。默认情况下,作业对象中的进程创建的新进程属于同一作业对象。调用 TerminateJobObject 将终止作业对象中的所有关联进程。 p>

I will jump right in, to be brief and descriptive:

C++, Windows API

I am creating child processes using CreateProcess to run external (command-line) applications. I have built in a time-out, and if the child process has not returned normal execution by that time, I wish to force termination on that child process.

Ideally, I would like for that child process to act the same as if it had called ExitProcess, or as if a Ctrl+C was sent to its console (which calls ExitProcess from the default console control handler).

My solution so far has been the use of TerminateProcess to kill the child forcefully. This does force the child to terminate immediately, but unfortunately if that child spawned any children of its own they are left to run until their "natural" completion.

Is there a way to tell the child process to call ExitProcess, or to force all of the child's children to also terminate when TerminateProcess is called?

These external applications are beyond my control, and as such I can not modify them to provide a custom work-around.

Assume no knowledge of grand-child processes (names/pids/etc) that would allow me to manually call TerminateProcess on grand-child processes individually. Although this could be done by manually enumerating all processes, mapping process relationships, and tracking all processes, I do not consider this a valid solution except as the absolute last resort.

Thank you for your time.

解决方案

You can use Job objects to kill all the processes as a unit. You create a job object via the CreateJobObject API, and assign a process to it with AssignProcessToJobObject. New processes created by a process in a job object belong to the same job object by default. Calling TerminateJobObject will terminate all associated processes in the job object.

这篇关于终止子进程时终止所有(grand)子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆