通过内存映射实现进程间通信

send.cpp
#include <stdio.h>
#include <iostream>
#include <windows.h>

using namespace std;

int main( int argc, char **argv){
  HANDLE hMapFile = OpenFileMapping(
      FILE_MAP_ALL_ACCESS,
       false,
       "ShareFile"
      );
   if(hMapFile == NULL){
    cout << "获取内存映射文件失败" << endl;
     return 0;
  }
  LPVOID lpMapAddress = MapViewOfFile(
      hMapFile,
      FILE_MAP_ALL_ACCESS,
      0,
      0,
      0
      );
   if(lpMapAddress == NULL){
    cout << "内存映射文件申请失败" << endl;
     return 0;
  }

  cout << ( char *)lpMapAddress << endl;
  UnmapViewOfFile(lpMapAddress);
   return 0;
}
recv.cpp
 
#include <stdio.h>
#include <iostream>
#include <windows.h>

using namespace std;
int main( int argc, char **argv){
  HANDLE hMapFile = CreateFileMapping(
      INVALID_HANDLE_VALUE,
      NULL,
      PAGE_READWRITE,
      0,
      4*1024,
       "ShareFile"
      );
   if(hMapFile == NULL){
    cout << "分配内存空间出错" << endl;
     return 0;
  }

  LPVOID lpMapAddress = MapViewOfFile(
      hMapFile,
      FILE_MAP_ALL_ACCESS,
      0,
      0,
      0
      );
   if(lpMapAddress ==    NULL){
    cout << "申请内存失败" << endl;
     return 0;
  }
   char buf[4096];
  cin >> buf;
  lstrcpy(( char*)lpMapAddress,buf);
   int i = 0;
here:
  cin >> i;
   if(i == 0){
     goto here;    
  }
  UnmapViewOfFile(lpMapAddress);
   return 0;
}
 
 
 

你可能感兴趣的:(职场,内存,休闲,进程间通信)