The easiest way to transmit this handle seems to be by putting the Handle in the commandline arguments of CreateProcess
That is one way to do it, but it is not the only way.
Another simple way is to have Parent
send its process ID from GetCurrentProcessId()
to Kid
, and then Kid
can use OpenProcess()
to get a handle to Parent
.
there is no way I can see to get the Parent's Handle inside Parent.
GetCurrentProcess()
, which returns a pseudo-handle representing the calling process. All APIs that accept a process handle will accept this pseudo-handle when used in the context of the calling process.
But, for purposes of passing the calling process's handle to another process, Parent
would have to use DuplicateHandle()
to convert the pseudo-handle into a real handle (set Parent
as both source and target process). This is documented behavior.
GetCurrentProcess
returns a weird non-value, and DuplicateHandle
doesn't work without having the Kid's Handle
After Parent
has duplicated the pseudo-handle from GetProcessHandle()
into a real handle, it can then pass that duplicate to Kid
on the command line. Just make sure the duplicate is inheritable, and then use bInheritHandles=TRUE
in the CreateProcess()
call, or pass a STARTUPINFOEX
to CreateProcess()
containing a PROC_THREAD_ATTRIBUTE_HANDLE_LIST
(see Programmatically controlling which handles are inherited by new processes in Win32).
Impossible, since I need to create the Kid to get a Handle to it
If you don't want to use inheritable handles, then Parent
can alternatively create Kid
without passing any handle on the command line, then duplicate the GetCurrentProcess()
pseudo-handle with Kid
as the target process, then use an IPC mechanism of your choosing to send the duplicate to Kid
after it is already running.
but CreateProcess
is also the only chance to send the Parent's Handle to the Kid
No, it is not the only way. IPC is another way.