Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1689846
  • 博文数量: 584
  • 博客积分: 13857
  • 博客等级: 上将
  • 技术积分: 11883
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-16 09:34

分类: WINDOWS

2010-09-23 16:31:35

进程A写数据,进程B读数据;

进程A:

#include "stdafx.h"

#include

#include
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
#include
#include
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;
}

阅读(863) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~