Hector
Hector

Reputation: 1220

Obtaining a handle to a JobObject the process is running under

I can check if my process is in a job via IsProcessInJob with null. But I need a handle to this job. How do I go about this?

We have an automation system that wraps processes in job objects. However we have to call a script provided to us which is launching a process outside of this job object. So we need to manually add that process so that if the job fails and has to be killed it is also killed.

Upvotes: 0

Views: 310

Answers (2)

Harry Johnston
Harry Johnston

Reputation: 36328

Windows provides no supported method to open the job object associated with your process; it is the responsibility of the process that creates the job object to provide a way for other processes to find it, if it is desirable that they are able to do so. However, since the only reason you wanted to put the child into the job was so that it could be killed by the automation system, there is an alternative solution.

Instead of trying to put the child into the existing job object, create a new job object, one under your own control, and assign the child to it. Set the JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE basic limit flag so that the child (and any children it may have) will be killed when your job object is deleted, and make sure that your handle to the job object isn't inheritable.

If the automation system kills your process, or if it exits for any other reason, Windows will automatically close the handle and delete the job object, killing the child processes as desired.

Upvotes: 2

Hector
Hector

Reputation: 1220

Harry Johnstons suggestion worked.

If the only reason to put the child into the job is so that it can be killed, you might be able to do that another way. Put the child into a newly created job object, with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE set, and make sure the job handle isn't inheritable. If your process is killed, the job handle will be closed, causing the child to be killed.

Upvotes: 0

Related Questions