内存映射文件共享数据原理:系统调用CreateFileMapping之后,以后其它进程可以通过句柄命名来打开另一进程的内存映射文件映射句柄,得到这个句柄之后通过映射(MapViewOfFile)来访问共享数据。
// ProcessTransCreateFileMap.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <windows.h> #include <tchar.h> using namespace std; #define MAX_SIZE_SHARE 1024 int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFileMap = ::CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,MAX_SIZE_SHARE,TEXT("TestFileMap")); if(hFileMap != NULL) { if(::GetLastError() == ERROR_ALREADY_EXISTS) { PBYTE pView = (PBYTE)MapViewOfFile(hFileMap,FILE_MAP_READ | FILE_MAP_WRITE,0,0,0); if(pView != NULL) { TCHAR szBuf[1024] = {0}; _tcscpy_s(szBuf,1024,(TCHAR * )pView); wcout<<L"the other process data is :"<<szBuf <<endl; UnmapViewOfFile(pView); } else { wcout<<L"map failed!"<<endl; } ::CloseHandle(hFileMap); } else { PBYTE pView = (PBYTE)MapViewOfFile(hFileMap,FILE_MAP_READ | FILE_MAP_WRITE,0,0,0); if(pView != NULL) { TCHAR szBuf[] = {TEXT("this is a demo!!!!")}; ZeroMemory(pView,MAX_SIZE_SHARE); CopyMemory(pView,szBuf,(_tcslen(szBuf) + 1) * sizeof(TCHAR)); cout<<"already write a data "<<endl; UnmapViewOfFile(pView); } else wcout<<L"map failed!"<<endl; } } system("pause"); return 0; }