前言
windows 许多应用程序会在运行的时候创建一些数据,并需要将这些数据传输给其他进程,或者和其他进程共享某块内存。
可以使用 CreateFileMapping 并在使用时候第一个参数传入 INVALID_HANDLE_VALUE 。告诉系统创建的文件映射对象的物理存储器不是磁盘上的文件,而是从页交换文件中调拨物理存储器(就是从内存上分配共享内存的意思)。
使用例子
进程B 向共享内存写数据
//写进程
#include <iostream>
#include <windows.h>
#include <process.h>
#include <stdlib.h>
#include <conio.h>
#include <tchar.h>
#include <string.h>
using namespace std;
#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
int main()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, //default security
PAGE_READWRITE, //read/write access
0, //maximum object size (high order
BUF_SIZE, //maximum object size (low order
szName //name of mapping object
);
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError());
return 1;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile,//handle to map object
FILE_MAP_ALL_ACCESS,//read/write permission
0,
0,
BUF_SIZE
);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file ()%d.\n"), GetLastError());
CloseHandle(hMapFile);
return 1;
}
HANDLE rst = CreateEvent(NULL, FALSE, FALSE, L"ttt");
while (1)
{
TCHAR s[BUF_SIZE];
cout << "B process : plz input sth.to be transfered to A process" << endl;;
wcin >> s;
memcpy((PVOID)pBuf, s, BUF_SIZE);
SetEvent(rst);
}
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
}
进程A:向共享内存读数据
//读进程
#include <iostream>
#include <windows.h>
#include <process.h>
#include <stdlib.h>
#include <conio.h>
#include <tchar.h>
#include <string.h>
using namespace std;
#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
int main()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, //default security
PAGE_READWRITE, //read/write access
0, //maximum object size (high order
BUF_SIZE, //maximum object size (low order
szName //name of mapping object
);
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"), GetLastError());
return 1;
}
pBuf = (LPTSTR)MapViewOfFile(hMapFile,//handle to map object
FILE_MAP_ALL_ACCESS,//read/write permission
0,
0,
BUF_SIZE
);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file ()%d.\n"), GetLastError());
CloseHandle(hMapFile);
return 1;
}
HANDLE rst = CreateEvent(NULL, FALSE, FALSE, TEXT("ttt"));
while (1)
{
WaitForSingleObject(rst, INFINITE);
cout << "A process : receive some sth from B process" << endl;
wcout << pBuf << endl;
//_getch();
}
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
}
运行
进程B写入数据
同时进程A收到数据