进程间通信——共享内存(CreateFileMapping+MapViewOfFile)

代码比较少,直接贴代码。发送端和接收端的代码基本相同。

发送端

// ShareMemory_Send.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 

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 
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)_第1张图片

然后运行接收端打印数据

进程间通信——共享内存(CreateFileMapping+MapViewOfFile)_第2张图片

你可能感兴趣的:(Windows)