CreateProcessWithLogonW and AssignProcessToJobObje

2019-02-19 10:27发布

问题:

I have a Windows service (under WinXP SP2), running under the LocalSystem account, that launches processes using CreateProcessWithLogonW. In order to clean up child processes, I'm trying to use a job object and TerminateJobObject.

MSDN states that the job handle must have JOB_OBJECT_ASSIGN_PROCESS access right, which it has since it's created via CreateJobObject. The process handle must have PROCESS_SET_QUOTA and PROCESS_TERMINATE rights. I think it has them since TerminateProcess and SetProcessWorkingSetSize both return with no error.

Though, AssignProcessToJobObject fails with errno 5 (Access denied). Everything works fine if I replace CreateProcessWithLogonW with a simple CreateProcess.

Am I missing something or is what I'm trying to do impossible ?

Edit: It seems that svchost.exe, which actually creates the process when CreateProcessWithLogonW is used, already assigns the process to an anonymous job. The CREATE_CREAKAWAY_FROM_JOB flag is ignored by this function. So the real question is: is there a way to prevent svnhost from assigning the process to a job ?

回答1:

From Jeff Lawson on MSDN:

Interactions with Win32 Job Objects

CreateProcessWithLogonW executes the new process as a child of the Secondary Logon service, which has the outcome of making the process escape any Job Object membership/restrictions even if the Job Object did not allow breakaway.

Furthermore, the Secondary Logon service automatically creates its own new Job Object and assigns the new process into it. As such, it is not possible for the caller to explicitly assign the new process to any other Job Object (since a process may only be assigned to one Job Object, and can never be removed from a Job Object once it has been assigned to one).

Does each new process need a different logon? Otherwise, you could create a single process with the new logon and have it spawn new process using CreateProcess that could then be associated with a Job Object.