进程间通信——共享内存(CreateFileMapping+MapViewOfFile)
生活随笔
收集整理的這篇文章主要介紹了
进程间通信——共享内存(CreateFileMapping+MapViewOfFile)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼比較少,直接貼代碼。發送端和接收端的代碼基本相同。
發送端
// ShareMemory_Send.cpp : Defines the entry point for the console application. //#include "stdafx.h" #include <WINDOWS.H>BOOL Send() {//創建FileMapping對象HANDLE hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,0x1000,TEXT("shared"));if (NULL == hMapObject){printf("創建文件映像失敗\n");return FALSE;}//將FileMapping對象映射到自己的進程HANDLE hMapView = MapViewOfFile(hMapObject,FILE_MAP_WRITE,0,0,0);if (NULL == hMapView){printf("內存映射失敗\n");return FALSE;}//寫入數據memset((char*)hMapView,0,0x1000);strcpy((char*)hMapView,"Test shared memory.");return TRUE; } int main(int argc, char* argv[]) {Send();return 0; }接收端
// ShareMemory_Recv.cpp : Defines the entry point for the console application. //#include "stdafx.h" #include <windows.h> BOOL Recv() {//創建FileMapping對象HANDLE hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,0x1000,TEXT("shared"));if (NULL == hMapObject){printf("共享內存失敗\n");return FALSE;} //將FileMapping對象映射到自己的進程HANDLE hMapView = MapViewOfFile(hMapObject,FILE_MAP_WRITE,0,0,0);if (NULL == hMapView){printf("內存映射失敗\n");return FALSE;}//讀取數據char szBuffer[0x1000] = {0};memcpy(szBuffer,hMapView,0x1000);printf("%s\n",szBuffer);return TRUE; }int main(int argc, char* argv[]) {Recv();return 0; }運行結果
先讓發送端程序跑起來,不要結束,否則FileMapping會被釋放。
然后運行接收端打印數據
總結
以上是生活随笔為你收集整理的进程间通信——共享内存(CreateFileMapping+MapViewOfFile)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 进程间通信——自定义消息方式实现(Set
- 下一篇: 进程间通信——匿名管道