How to get a handle to a JobObject without knowing

2019-02-15 16:54发布

问题:

My application is running in a job. I want to get a Handle to this Jobobject using OpenJobObject so i can later use this handle. The problem is, that i don't know the jobs name, and with passing NULL to the Job name it gives error 87 ( The parameter is incorrect ) back.

This is how i tried it:

HANDLE handle = OpenJobObject( JOB_OBJECT_QUERY, FALSE, NULL );
if ( !handle  ) printf( "\nError %d", GetLastError() );
else printf( "\nOK" );

I also found this on MSDN: An application cannot obtain a handle to the job object in which it is running unless it has the name of the job object. However, an application can call the QueryInformationJobObject function with NULL to obtain information about the job object.

So my question is, is it possible to get somehow a handle to the JobObject in which my application is running? Or get the name of the job my application is running in?

Thanks!

Update:
My code so far: http://pastebin.com/aJ7XMmci Right now, i'm getting Error 87 ( The parameter is incorrect ) from SetInformation :(

回答1:

OK, doesn't look like there's any supported method. That doesn't mean it can't be done! :-)

To enumerate all the handles in the system, see this question. The sample code here filters the handles and only looks for those belonging to a particular process, but that's easy to change. You might need to enable debug privilege first.

For each handle, duplicate it into your process, then call IsProcessInJob to find out whether it's the right handle or not.

Once you've got that working, check whether SYSTEM_HANDLE.ObjectTypeNumber is always the same for job objects. It probably is (on any given OS, at least) in which case you can drastically increase the efficiency of the code by only checking job object handles.

You could perhaps also filter to just the process running the Secondary Logon service, since this seems to be what creates the job objects for runas.

(If you do get this working, please post code - it could be very useful for future visitors.)



标签: c windows jobs