FileMapping之进程通信
读取端
#include <iostream>
#include <Windows.h>
#include <sddl.h>
#include <thread>
#include <chrono>
#pragma comment(lib, "Advapi32.lib")
char* pData = nullptr;
int main()
{
// create event handle
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
// common user support
PSECURITY_DESCRIPTOR pSD = NULL;
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
L"D:(A;;GA;;;AU)(A;;GA;;;SY)",
1,//SDDL_REVISION_1,
&pSD,
NULL)) {
}
sa.lpSecurityDescriptor = pSD;
HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 0x100, L"FileMappingTest");
if (hMapping != NULL)
{
pData = (char*)MapViewOfFile(hMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
else {
int nCode = GetLastError();
std::cout << "Create file mapping failed: " << GetLastError() << "\n";
return -1;
}
int nIndex = 0;
while (1) {
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
if (strlen(pData)) {
std::cout << "Data: " << pData << "\n";
}
if ((++nIndex) >= 20)break;
}
getchar();
UnmapViewOfFile(pData);
CloseHandle(hMapping);
return 0;
}
2、写入端
#include <iostream>
#include <Windows.h>
#include <sddl.h>
#include <thread>
#include <chrono>
#pragma comment(lib, "Advapi32.lib")
char* pData = nullptr;
int main()
{
const char* sharessdl = "D:P(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;OICI;GR;;;IU)";
SECURITY_ATTRIBUTES security;
ZeroMemory(&security, sizeof(security));
security.nLength = sizeof(security);
ConvertStringSecurityDescriptorToSecurityDescriptorA(
sharessdl,
SDDL_REVISION_1,
&security.lpSecurityDescriptor,
NULL);
HANDLE hMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"FileMappingTest");
if (hMapping != NULL)
{
pData = (char*)MapViewOfFile(hMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
#if 1
#if 0
const char* pSrc = "exit";
#else
DWORD nPid = GetCurrentProcessId();
std::string strPid = std::to_string(nPid);
const char* pSrc = strPid.c_str();
//const char* pSrc = "34600";
#endif
strcpy_s(pData, strlen(pSrc) + 1, pSrc);
UnmapViewOfFile(pData);
std::cout << "Set share data: " << strPid << "\n";
#endif
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, L"EventFileMapping");
if (NULL != hEvent) {
SetEvent(hEvent);
CloseHandle(hEvent);
std::cout << "Notify event\n";
}
else {
std::cout << "Open event error: " << GetLastError();
}
}
else {
int nCode = GetLastError();
std::cout << "Create file mapping failed: " << GetLastError() << "\n";
return -1;
}
getchar();
CloseHandle(hMapping);
return 0;
}
注意事项
1、32和64位程序创建的FileMapping可直接访问,没有位数限制
2、FileMapping可通过mutex和event进行同步
3、如果是服务,Mapping名字需要加Global\前缀(Event也一样),才能全局访问