By far the most common way for a child process to determine the handle value of the kernel object that it's expecting is to have the handle value passed as a command-line argument to the child process. The
child process's initialization code parses the command line (usually by calling sscanf) and extracts the handle value. Once the child has the handle value, it has unlimited access to the object. Note that
the only reason handle inheritance works is because the handle value of the shared kernel object is identical in both the parent process and the child process; this is why the parent process is able to pass
the handle value as a command-line argument.
///
//在进程A中将H_Event定义为可继承的,在A创建B的同时,在参数bInheritHandles=true,表明B可以继承A中可继承的句柄
//这样B就继承了A中的H_Event,同时Inherited_Test等待Event的信号,而进程A在等待B结束
//通过CCommandlines传递H_Event,进程B中将该事件改变了有信号状态
///进程A程序
#include <windows.h>
#include <process.h>
#include <stdio.h>
HANDLE H_Event;
typedef unsigned(__stdcall *PTHREAD_START)(void *);
DWORD WINAPI Inherited_Test(PVOID pvparam)
{
WaitForSingleObject(H_Event,INFINITE);
printf("Main_Process_Inherited:%d/n",GetCurrentThreadId());
return 0;
}
void main( void )
{
SECURITY_ATTRIBUTES ps;
ps.bInheritHandle=true;
ps.nLength=sizeof(ps);
ps.lpSecurityDescriptor=NULL;
H_Event=CreateEvent(&ps,false,false,NULL);
ResetEvent(H_Event);
HANDLE H_Wait[2];
DWORD ThreadID;
H_Wait[0]=(HANDLE)_beginthreadex(NULL,0,(PTHREAD_START)Inherited_Test,0,NULL,(unsigned*)&ThreadID);
/
TCHAR CCommandlines[20];
STARTUPINFO si={sizeof(si)};
PROCESS_INFORMATION pi;
wsprintf(CCommandlines,"%d",H_Event);
printf("%s/n",CCommandlines);
TCHAR Capplication_name[MAX_PATH];
GetCurrentDirectory(sizeof(Capplication_name)/sizeof(TCHAR),Capplication_name);
lstrcat(Capplication_name,"//debug//cpp2.exe ");
BOOL ret=CreateProcess(Capplication_name,CCommandlines,NULL,NULL,true,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi);
if(ret)
{
printf("CreateProcess Finish......../n");
CloseHandle(pi.hThread);
H_Wait[1]=pi.hProcess;
WaitForMultipleObjects(2,H_Wait,true,INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(H_Wait[0]);
CloseHandle(H_Event);
}
return;
}
进程B程序
#include <windows.h>
#include <process.h>
#include <stdio.h>
void main( int argc, /* Number of strings in array argv */
char *argv[], /* Array of command-line argument strings */
char **envp ) /* Array of environment variable strings */
{
printf("/n");
printf("/n");
printf("Already in.......Child Process %d/n",argc);
int count;
/* Display each command-line argument. */
printf( "/nCommand-line arguments:/n" );
for( count = 0; count < argc; count++ )
printf( " argv[%d] %s/n", count, argv[count] );
HANDLE Get_Inheritd_Handle;
sscanf(argv[0],"%d",&Get_Inheritd_Handle);
printf("HANLE VALUE:%d/n",Get_Inheritd_Handle);
SetEvent(Get_Inheritd_Handle);
MessageBox(NULL,"OK",NULL,MB_OK);
return;
}