This has been asked before but I can't find a definitive answer, in code.
I open a process, ProcessA (with PID 1234). This process opens a child process, ProcessAB (PID 5678). After I'm done I terminate ProcessA but I still have the lingering of ProcessAB.
How do I terminate the whole process tree? What I mean, how do I make sure that if I terminate the process I opened I am also terminating all the associated processes?
Thanks
Code is appreciated.
The following is for Linux, but I hope it helps for Windows with some adaptation.
When you fork(), save the return value, which is the pid of the child process, then when the parent is about to exit, kill() the pid.
If you have multiple child processes, you can send the kill to the process group. By default, the child processes have the same pgid as the parent.
To kill a whole tree with ALL!!! childs:
Check this thread for grouping processes within a "job".
If that does not work for you, a home grown approach might go as follows:
Sample code:
There's How To Kill a Process Tree, but it's in C#. I don't think it's too hard to port that to C.
See NtQueryInformationProcess Function and TerminateProcess Function.
Use Job Objects.
It's the closest thing to a unix 'process group' that windows has to offer.
Job Objects allow you to indicate a child process (and all its children) can be managed together, esp. for being killed. Unlike unix, as of this writing 'job objects' cannot be nested. Which means if a parent creates a job object for a child, all that child's children cannot themselves use Job Objects (which is a /severe/ limitation IMHO, like a file system that only allows one level of sub directories).
@mjmarsh answers needs recursion for the homebrew case, otherwise it is the right one. Creating job objects is better that the below when you can.