Select which handles are inherited by child process Select which handles are inherited by child process windows windows

Select which handles are inherited by child process


If the output file handle is inherited by the child process, then that is because the code in the parent process that opened the file explicitly stated that the file handle should be inheritable. It passed a value for the lpSecurityAttributes parameter of CreateFile. The default state is for the handle to not be inheritable.

It seems to me that your process-creating class shouldn't try to second-guess its caller, who has already opened the file.

However, if you have special knowledge of exactly which handles the new process needs, then as of Windows Vista, there is a mechanism for specifying which handles should be inherited. When you prepare to call CreateProcess, use a STARTUPINFOEX structure instead of the usual STARTUPINFO. It has an lpAttributeList member. Allocate and initialize it, and then use UpdateProcThreadAttribute with PROC_THREAD_ATTRIBUTE_HANDLE_LIST to set the list of handles to be inherited. All the handles need to be inheritable, and you still need to specify bInheritHandles = TRUE when you call CreateProcess. You also need to include EXTENDED_STARTUPINFO_PRESENT in the dwCreationFlags parameter. Raymond Chen demonstrated the technique in an article in 2011.

If that added functionality isn't available to you, then you could certainly try to enumerate all your program's open handles and set all their inheritance properties with SetHandleInformation, but that seems to be beyond the scope of a function whose job is to create child processes. Let the code that creates the handles worry about whether they should be inheritable.


You can use SetHandleInformation to clear the HANDLE_FLAG_INHERIT bit on your output handle, this will prevent the child process from inheriting it.

If this flag is set, a child process created with the bInheritHandles parameter of CreateProcess set to TRUE will inherit the object handle.


It's noteworthy to say that using SetHandleInformation is prone to race conditions in case multiple threads create processes. Here is a test sequence:

thread 1: HANDLE h = ::CreateFile(..., lpSecurityAttributes = NULL, ...);thread 2: ::CreateProcess(..., inherit_handles=TRUE, ...);thread 1: ::SetHandleInformation (h, HANDLE_FLAG_INHERIT, FALSE);// the above line is useless, because child process created by thread 2 has already inherited the handle

The proper way is to always specify handle inheritance during handle creation, such as:

SECURITY_ATTRIBUTES sa = { 0 };sa.bInheritHandles = FALSE;HANDLE h = ::CreateFile(..., lpSecurityAttributes = &sa, ...);

Note that Microsoft's implementation of fopen() has a special mode value "N" that disables handle inheritance.

P.S. This is an old thread, but still has a lot of views, so don't kill me for adding to it :)