Chapter17— Memory-Mapping Files 进程间共享数据进行通信
第十七章的实例有个利用 Memory-Mapped File 来实现进程间共享数据和通信。
Step1:调用 CreateFileMapping 函数创建一个 Memory-Mapped File Object。该函数的原型如下:
代码示例
#include <windows.h>#include <TCHAR.H>#include <stdio.h>void main(){ int choice; HANDLE hFile_Map = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4 * 1024, TEXT("MMFSharedData")); if (hFile_Map == NULL) { printf("Failed to create file mapping!\n"); getchar(); return; } else if (GetLastError() == ERROR_ALREADY_EXISTS) { printf("Mapping already exists - not created.\n"); getchar(); } // File mapping created successfully. // Map a view of the file into the address space. PVOID pView = MapViewOfFile(hFile_Map, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (NULL == pView) { printf("Failed to map view of file.\n"); getchar(); return; } while (true) { getchar(); system("cls"); printf("\n\t1.写入 mapping file 内容."); printf("\n\t2.读取 mapping file 内容."); printf("\n\t3.退出程序"); printf("\n\n请输入你的选择序号:"); scanf("%d", &choice); if (choice == 3) break; switch (choice) { case 1: printf("输入要写入的内容:"); scanf("%s", pView); break; case 2: printf("显示已写入的内容:"); printf("%s\n", pView); break; default: printf("你的选择序号有误。\n"); break; } getchar(); } UnmapViewOfFile(pView); CloseHandle(hFile_Map); }《windows核心编程》(笔记)系列文章是本人看《windows核心编程》时的一些学习笔记,有疏忽之处,欢迎各位网友指正。QQ邮箱:job.zhanghui@qq.com