hFile = CreateFile("robots.txt",GENERIC_READ,FILE_SHARE_READ,&sa,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(hFile == INVALID_HANDLE_VALUE){
printf("Create file handle failed.(%d)\n",GetLastError());
CloseHandle(hFile);
return 1;
}
lpFileBuffer = HeapAlloc(GetProcessHeap(),0,MAX_BUFFER_SIZE);
while(1){
iResult = ReadFile(hFile,lpFileBuffer,MAX_BUFFER_SIZE,&dwBytesInFile,NULL);
if(!iResult){
printf("Read file failed.(%d)\n",GetLastError());
CloseHandle(hFile);
return 1;
}
if(dwBytesInFile > MAX_BUFFER_SIZE){
HeapReAlloc(GetProcessHeap(),0,lpFileBuffer,dwBytesInFile);
ZeroMemory(lpFileBuffer,dwBytesInFile);
}else{
break;
}
}
printf("Parent process id:%d\n",GetCurrentProcessId());
printf("[Parent]The value of the handle is %u\n",hFile);
printf("[Parent]The index of the handle in table is:%u\n",((DWORD)hFile/4));
printf("[Parent]The content of the robots.txt:\n%s\n\n\n",lpFileBuffer);
//最好将要传递给子进程参数命令行的值存放在缓存中
LPSTR lpCommandLine; //定义一个字符串指针以存放内核对象句柄
lpCommandLine = (LPSTR)HeapAlloc(GetProcessHeap(),0,1024); //为字符串指针分配内存
ltoa((DWORD)hFile,lpCommandLine,10); //将HANDLE句柄转换为字符串类型储存
if(!CreateProcess("ChildProcess.exe",lpCommandLine,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi)){
printf("Create child process failed.(%d)\n",GetLastError());
return 1;
}
printf("Child process created.\n\n\n");
CloseHandle(hFile);
WaitForSingleObject(pi.hProcess,INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
子程序:
#include <Windows.h>
#include <stdio.h>
#define MAX_BUFFER_SIZE 4096
int main(int argc,char * argv[]){
int iResult;
LPVOID lpFileBuffer;
DWORD dwBytesHasRead;
LPSTR commandLine = GetCommandLine();
HANDLE hChildFile = (HANDLE)atol(commandLine);
lpFileBuffer = HeapAlloc(GetProcessHeap(),0,MAX_BUFFER_SIZE);
while(1){
iResult = ReadFile(hChildFile,lpFileBuffer,MAX_BUFFER_SIZE,&dwBytesHasRead,NULL);
if(!iResult){
printf("Read file failed.(%d)\n",GetLastError());
CloseHandle(hChildFile);
return 1;
}
if(dwBytesHasRead > MAX_BUFFER_SIZE){
HeapReAlloc(GetProcessHeap(),0,lpFileBuffer,dwBytesHasRead);
ZeroMemory(lpFileBuffer,dwBytesHasRead);
}else{
break;
}
}
printf("Child process id:%d\n",GetCurrentProcessId());
printf("[Child]The value of the handle is %u\n",(DWORD)hChildFile);
printf("[Child]The index of the handle in table is:%u\n",((DWORD)hChildFile/4));
printf("[Child]The content of the robots.txt:\n%s\n\n\n",lpFileBuffer);
CloseHandle(hChildFile);
return 0;
}
执行后结果如下:
E:\me\SdkTest\TestHandle\Debug>TestHandle.exe
Parent process id:7452
[Parent]The value of the handle is 48
[Parent]The index of the handle in table is:12
[Parent]The content of the robots.txt:
Keep going on,dude! byPnig0s1992t
Child process created.
Child process id:4684
[Child]The value of the handle is 48
[Child]The index of the handle in table is:12
[Child]The content of the robots.txt:
?