共享内存实现进程间通信
程序代码:
#include <windows.h> #include <stdio.h> int main() { int handle = 0xFFFFFFFFFFFFFFFF; void* handle2 = INVALID_HANDLE_VALUE; // Create a paging file-backed MMF to contain the edit control text. // The MMF is 4 KB at most and is named MMFSharedData. static HANDLE s_hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4 * 1024, ("MMFSharedData")); if (s_hFileMap != NULL) { if (GetLastError() == ERROR_ALREADY_EXISTS) { puts("Mapping already exists - not created."); CloseHandle(s_hFileMap); // See if a memory-mapped file named MMFSharedData already exists. HANDLE hFileMapT = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, TEXT("MMFSharedData")); if (hFileMapT != NULL) { // The MMF does exist, map it into the process's address space. PVOID pView = MapViewOfFile(hFileMapT, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (pView != NULL) { // Put the contents of the MMF into the edit control. puts((PTSTR) pView); UnmapViewOfFile(pView); } else { puts("Can't map view."); } CloseHandle(hFileMapT); } else { puts("Can't open mapping."); } } else { // File mapping created successfully. // Map a view of the file into the address space. PVOID pView = MapViewOfFile(s_hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (pView != NULL) { // Put edit text into the MMF. sprintf((char*)pView, "%s", "Some test data"); // Protect the MMF storage by unmapping it. UnmapViewOfFile(pView); } else { puts("Can't map view of file."); } } } else { puts("Can't create file mapping."); } return 0; }
[此贴子已经被作者于2016-1-28 10:16编辑过]