进程间通信(3):共享内存

管道通信在我之前的博客文章《进程间通信(1):匿名管道》《进程间通信(2):命名管道》中进行了讲述,管道通信有其自身的缺点,管道的缓冲区是受限的,封装的网络操作,也会影响通信的速度,操作不当很容易阻塞。


共享内存操作一般被认为是最快的进程间通信方式,在系统内存中开辟一块内存区,分别映射到各个进程的虚拟地址空间中,任何一个进程操作了内存区都会反映到其他进程中。这种方式可以像访问自己的私有空间一样访问共享内存区。要说缺点,就是共享内存的数据同步比较困难,编程难度较大,不注意的话会造成数据的混乱。


结合例子进行讲解,例程如下。在服务器端通过CreateFileMapping函数创建文件映射,此处映射文件的名称作为共享内存区域的唯一标识,供其他进程索引。通过MapViewOfFile函数获得内存区域的首地址,然后就可以将数据拷贝到共享内存区域,通知给其他进程。显而易见,要首先启动服务器端程序。


文章中示例代码的完整工程文件可在http://download.csdn.net/download/ezhchai/9895833中下载


服务器端代码:

// SharedMemorySrv.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
	HANDLE hMapFile = NULL;
	char* pStr;
	// Create the file mapping object.    
	hMapFile = CreateFileMapping(
		INVALID_HANDLE_VALUE,   // Use paging file - shared memory    
		NULL,                   // Default security attributes    
		PAGE_READWRITE,         // Allow read and write access    
		0,                      // High-order DWORD of file mapping max size    
		256,					// Low-order DWORD of file mapping max size    
		(LPCWSTR)"MapTrans"		// Name of the file mapping object    
	);
	if (NULL == hMapFile)
	{
		cout << "CreateFileMapping failed! Error: " << GetLastError() << endl;
		return 1;
	}
	cout << "The file mapping MapTrans is created! " << endl;
	// Map a view of the file mapping into the address space of the current process.   
	pStr = (char*)MapViewOfFile(
		hMapFile,               // Handle of the map object    
		FILE_MAP_WRITE,			// Read access    
		0,                      // High-order DWORD of the file offset     
		0,						// Low-order DWORD of the file offset     
		256						// The number of bytes to map to view  
	);
	if (NULL == pStr)
	{
		cout << "MapViewOfFile failed! Error: " << GetLastError() << endl;
		return 2;
	}
	cout << "The file view is mapped!" << endl;
	strcpy_s(pStr, 20, "ezhchai");				//write data to the shared memory
	cout << "This message is written to the view: " << "ezhchai" << endl;
	getchar();
	UnmapViewOfFile(pStr);
	CloseHandle(hMapFile);
	return 0;
}


客户端程序在服务器程序建立共享内存区域后,通过OpenFileMapping函数以共享内存文件名为标识,打开映射文件区域,同样通过MapViewOfFile函数获得内存区域的首地址,也就可以操作共享内存区域,实现进程间通信了。


客户端代码:

// SharedMemoryClt.cpp : 定义控制台应用程序的入口点。
//  
#include "stdafx.h"
#include <windows.h>    
#include <iostream>

using namespace std;

int main()
{
	HANDLE hMapFile = NULL;
	char* pStr;

	// Try to open the named file mapping identified by the map name.    
	hMapFile = OpenFileMapping(
		FILE_MAP_READ,          // Read access    
		FALSE,                  // Do not inherit the name    
		(LPCWSTR)"MapTrans"		// File mapping name     
	);
	if (NULL == hMapFile)
	{
		cout << "OpenFileMapping failed! Error: " << GetLastError() << endl;
		return 1;
	}
	cout << "The file mapping MapTrans is opened! " << endl;

	// Map a view of the file mapping into the address space of the current process.      
	pStr = (char*)MapViewOfFile(
		hMapFile,               // Handle of the map object    
		FILE_MAP_READ,          // Read access    
		0,                      // High-order DWORD of the file offset     
		0,						// Low-order DWORD of the file offset    
		256						// The number of bytes to map to view    
	);
	if (NULL == pStr)
	{
		cout << "MapViewOfFile failed! Error: " << GetLastError() << endl;
		return 2;
	}
	cout << "The file view is mapped!" << endl;
	puts(pStr);					// Read sdata from the shared memory
	getchar();
	UnmapViewOfFile(pStr);
	CloseHandle(hMapFile);
	return 0;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值