进程A写数据,进程B读数据;
进程A:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE lhShareMemory;
char* lpBuffer = NULL;
lhShareMemory = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE,
0, 10, "mySharedMemory");
if (NULL == lhShareMemory)
{
if (ERROR_ALREADY_EXISTS == GetLastError())
{
cout << "Already exists!";
}
else
{
cout << "Create Sheared Memory unsuccessfully!";
}
return 0;
}
lpBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_WRITE, 0, 0, 10);
if (NULL == lpBuffer)
{
cout << "Get Share memory unsuccessfully!";
return 0;
}
strcpy(lpBuffer, "hello");
cout << *(lpBuffer + 40) << endl;
Sleep(600000);
UnmapViewOfFile(lpBuffer);
return 0;
}
进程B:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE lhShareMemory;
char* lpcBuffer;
lhShareMemory = OpenFileMapping(FILE_MAP_READ, false, "mySharedMemory");
if (NULL == lhShareMemory)
{
cout << "Open share memory unsuccessfully!" << endl;
DWORD ldwError = GetLastError();
cout << ldwError;
return 0;
}
lpcBuffer = (char*)MapViewOfFile(lhShareMemory, FILE_MAP_READ, 0, 0, 100);
if (NULL == lpcBuffer)
{
cout << "Open share memory unsuccessfully!";
return 0;
}
for (int i = 0; i < 100; ++i)
{
cout << *(lpcBuffer + i);
}
UnmapViewOfFile(lpcBuffer);
return 0;
}