#include "stdafx.h"
#include <stdio.h>
#include <Windows.h>
#include <WinBase.h>
int _tmain(int argc, _TCHAR* argv[]){
SECURITY_ATTRIBUTES sa;
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle=TRUE;
sa.lpSecurityDescriptor=NULL;//必须这样指定,否则没有ZeroMemory的话可能是个非法的值
HANDLE shm=CreateFileMapping(INVALID_HANDLE_VALUE,&sa,PAGE_EXECUTE_READWRITE,0,20,"myfm");
if(INVALID_HANDLE_VALUE==shm){
printf("CreateFileMapping failed\n");
return 1;
}
int *ps=(int*)MapViewOfFile(shm,FILE_MAP_ALL_ACCESS,0,0,20);
*ps=33;
UnmapViewOfFile(ps);//这句要不要无所谓
//CloseHandle(shm);不能在这里Close,CloseHandle使得any error 变成2
STARTUPINFO StartupInfo;
ZeroMemory(&StartupInfo,sizeof(STARTUPINFO));
StartupInfo.cb=sizeof(STARTUPINFO);
PROCESS_INFORMATION ProcessInformation;
BOOL ret=CreateProcess(_T("..\\Debug\\client.exe"),0,0,0,
TRUE,CREATE_DEFAULT_ERROR_MODE,0,0,&StartupInfo,&ProcessInformation);
WaitForSingleObject(ProcessInformation.hProcess,INFINITE);
if(FALSE==ret){
printf("%d\n",GetLastError());
return 1;
}
ps=(int*)MapViewOfFile(shm,FILE_MAP_ALL_ACCESS,0,0,20);
printf("now *ps=%d\n",*ps);
if(!CloseHandle(shm)){
printf("CloseHandle failed\n");
return 1;
}
return 0;
}
|