Some time ago, I wrote about programmatically controlling which handles are inherited by new processes in Win32 by using the PROC_ to limit exactly which handles are inherited. That way, when you create a new process, you have precise control over which handles get inherited and don’t accidentally inherit handles created by unrelated components in your process.
A collegue of mine pointed out that you still have the reverse problem: Since handles must be marked as inheritable for them to participate in PROC_, if another thread calls CreateÂProcess with bInheritHandles = TRUE but without using PROC_, then they will accidentally inherit all of your handles.
This problem could have been avoided if the PROC_ allowed you to include non-inheritable handles, in which case they would be non-inheritable by normal CreateÂProcess but inheritable if explicitly opted back in. But alas, that’s not how it was designed.
Instead, you can create a helper process. All this helper process does is wait for the main process to exit, and then exit itself.
WaitForSingleObject(hMainProcess, INFINITE); ExitProcess(0);
This process doesn’t sound like it’s doing anything useful, and it’s not. But what makes it useful is not what it’s doing but rather what is done to it.
The components in the main process create their handles as non-inheritable. When they wants to create a process with specific inherited handles, they duplicate the desired handles into the helper process (as inheritable), and then build a PROC_ that lists those duplicates as handles to inherit. They also use the PROC_ to specify that the helper process is the parent process that the handles should be inherited from. Then they pass those thread attributes to CreateÂProcess, and the new process will inherit exactly those handles. Then they clean up by closing the handles in the helper process with the help of DuplicateÂHandle and DUPLICATE_.
Notice that multiple threads can simultaneously be operating on the helper process in this way, so you need only one helper process to service all your handle-inheritance-control needs.
This avoids the accidental inheritance problem because the handles that belong to the components in the main process are still marked non-inheritable, so any other code in the main process that does a CreateÂProcess will not inherit them.
0 comments
Be the first to start the discussion.