views:

152

answers:

1

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.

+1  A: 

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.

Michael
Thank you Michael. This is very promising and looks as though it perfectly solves this problem. Now to go read more and give it a shot! Thank you kindly for sharing your knowledge and experience.
KevenK
Job objects no longer work well as of Vista. Explorer puts programs started from a shortcut in a job, preventing you from doing the same with any child processes.
Hans Passant
I could not repro this behavior on my Win7 box - I wrote a small program that creates a job and adds itself to it. Works fine when launched by explorer via a shortcut.
Michael
@Michael: Thanks again. I've tested this with success on my environments. This is a solid solution to exactly the problem I was experiencing.@nobugz: Thank you for your warning, it is always best to know potential problems before blindly assuming something is perfect. I was able to find several resources that cite this problem, and the solution that came up was to include Vista appropriate UAC information in the manifest file to avoid this issue. See http://social.msdn.microsoft.com/forums/en-US/windowssecurity/thread/71c9599e-a3d5-4b79-bfc1-1800565c5b8a/Thank you both for the help!
KevenK