先开启进程1,然后在进程2中就可以获取进程1中的数据了, msdn中的例子如下:
// process1.cpp #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> #define BUF_SIZE 256 TCHAR szName[] = TEXT("Global\\MyFileMappingObject"); TCHAR szMsg[] = TEXT("Message from first process."); int _tmain() { HANDLE hMapFile; LPCTSTR pBuf; hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, BUF_SIZE, szName); if (hMapFile == NULL) { _tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError()); return 1; } pBuf = (LPTSTR)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d). \n"), GetLastError()); CloseHandle(hMapFile); return 1; } CopyMemory((void*)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR))); _getch(); UnmapViewOfFile(pBuf); CloseHandle(hMapFile); return 0; }
//process2.cpp #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> #pragma comment(lib, "user32.lib") #define BUF_SIZE 256 TCHAR szName[] = TEXT("Global\\MyFileMappingObject"); int _tmain() { HANDLE hMapFile; LPCTSTR pBuf; hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szName); if (hMapFile == NULL) { _tprintf(TEXT("Could not open file mapping object (%d). \n"), GetLastError()); return 1; } pBuf = (LPTSTR)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return 1; } MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK); UnmapViewOfFile(pBuf); CloseHandle(hMapFile); return 0; }