看windows下的进程间通信,第一个就是Filemapping,今天下午好好的看了下.试了半天写了两个小程序终于运行成功了...
program 1
1 #include<windows.h> 2 #include<iostream> 3 4 int main() 5 { 6 HANDLE hFile=CreateFile("e:\\kuan.txt",GENERIC_READ|GENERIC_WRITE, 7 FILE_SHARE_WRITE, 8 NULL, 9 OPEN_ALWAYS, 10 FILE_ATTRIBUTE_NORMAL, 11 NULL); 12 13 HANDLE hFileMapping=CreateFileMapping(hFile, 14 NULL, 15 PAGE_READWRITE, 16 0,0x00000110, 17 "kuan"); 18 19 if(hFileMapping==NULL) 20 { 21 std::cout<<"fmap invali"<<std::endl; 22 23 } 24 25 PBYTE pbFile=(PBYTE)MapViewOfFile(hFileMapping, 26 FILE_MAP_ALL_ACCESS ,0,0,0); 27 28 //*pbFile='B'; 29 char* pb="asdasdasdasdasdasdasdasdasdasd"; 30 memcpy(pbFile,pb,strlen(pb)); 31 //FlushViewOfFile(pbFile,0); 32 UnmapViewOfFile(pbFile); 33 getchar(); 34 CloseHandle(hFileMapping); 35 CloseHandle(hFile); 36 37 38 system("PAUSE"); 39 return 0; 40 }
program 2
1 #include<windows.h> 2 #include<iostream> 3 4 int main() 5 { 6 HANDLE hFilemapping=OpenFileMapping(FILE_MAP_ALL_ACCESS,0,"kuan"); 7 8 PBYTE pb=(PBYTE)MapViewOfFile(hFilemapping,FILE_MAP_ALL_ACCESS,0,0,0); 9 10 char *p="12131231241"; 11 *pb='A'; 12 //memcpy(pb,p,strlen(p)); 13 UnmapViewOfFile(pb); 14 //CloseHandle(hFilemapping); 15 return 0; 16 17 }
文件映射对象可以通过文件名访问,然后在其他程序中通过openfilemapping打开,注意openfilemapping第一个参数不同于createfilemapping的第三个参数flprotection,
openfilemapping是FILE_MAP_* ,createfilemapping是PAGE_**,为此第二个进程一直不能写入,但是能读出,这到是很神奇啊...