/************************************************************************/
/* 用内存映射来实现进程间数据通信 */
/* 转载请注明文章来自:http://blog.csdn.net/windows_nt */
/************************************************************************/
#include <Windows.h>
#include <iostream>
using namespace std;
// Tell the compiler to put this initialized variable in its own Shared
// section so it is shared by all instances of this application.
#pragma data_seg("Shared")
volatile LONG g_lApplicationInstances = 0;
#pragma data_seg()
// Tell the linker to make the Shared section readable, writable, and shared.
#pragma comment(linker, "/Section:Shared,RWS")
void main ()
{
//多个应用程序实例间数据共享,用来判别多少个应用程序实例
InterlockedExchangeAdd(&g_lApplicationInstances, 1);
printf("这是第 %d 个应用程序实例。\r\n", g_lApplicationInstances);
//内存映射实现进程间数据通信,可以在不同程序间实现通信
static HANDLE s_hFileMap = NULL;
// Create a paging file-backed MMF to contain the edit control text.
// The MMF is 4 KB at most and is named MMFSharedData.
s_hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0, 4 * 1024, TEXT("MMFSharedData"));
if (s_hFileMap != NULL)
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
printf("内存映射文件对象已经存在,现在读取内存映射并进行显示");
// 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.
printf("读取的数据为:\r\n %s", (char*)pView );
UnmapViewOfFile(pView);
}
else
{
printf("Can't map view.");
}
CloseHandle(hFileMapT);
}
else
{
printf("Can't open mapping.");
}
CloseHandle(s_hFileMap);
}
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)
{
printf("创建内存映射视图成功!\r\n");
// Put edit text into the MMF.
printf("请输入需要共享的数据(回车终止):\r\n");
cin >> (char*)pView;
// Protect the MMF storage by unmapping it.
UnmapViewOfFile(pView);
printf("你现在可以启动新的进程来读取刚才的数据进行测试了。\r\n");
}
else
{
printf("Can't map view of file.");
}
}
}
else
{
printf("Can't create file mapping.");
}
getchar();
getchar();
// This instance of the application is terminating
InterlockedExchangeAdd(&g_lApplicationInstances, -1);
return;
}