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

本文通过两个C++示例程序(send.cpp与recv.cpp)介绍了如何在Windows环境下使用内存映射文件进行进程间通信。示例展示了如何创建、打开及使用内存映射文件来实现数据共享。
510

被折叠的 条评论
为什么被折叠?



