Search code examples
c++winapiprocesskernel32win32-process

CreateProcess such that child process is killed when parent is killed?


Is there a way to call CreateProcess such that killing the parent process automatically kills the child process?

Perhaps using Create Process Flags?

Edit
The solution is to create a job object, place both parent and child in the job object. Whent he parent is killed the child is killed. I got the code from here: Kill child process when parent process is killed Take note of @wilx's comment about inherited handles.


Solution

  • Using jobs as Neil says is IMHO the best way. You can make the child processes get killed when the job owning process dies by setting JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the job object using SetInformationJobObject(). The job object handle will be closed when your parent process exits/dies. For this to work it is essential that the job handle is not inherited by the child processes. If you want to track also the grand-child processes then you will have to create your child processes suspended, add them to your job object and only then let them run.