I wrote a simple inter-process communication with a memory-mapped file. The code works relatively well, but I have a problem with the buffer that I’ll explain shortly. Here is the code (C++, Windows):
#define UNICODE #define _UNICODE #include <iostream> #include <tchar.h> #include <Windows.h> int wmain(int argc, wchar_t** argv) { if (argc != 2) { std::cout << "Usage: `win32mmap w` for writing, or `win32mmap r` for reading.n"; return -1; } HANDLE hMapFile; HANDLE hEvent; HANDLE isOpened = CreateEvent(NULL, true, false, L"IsOpened"); // To check if a `win32mmap w` runs if (wcscmp(argv[1], L"w") == 0) { SetEvent(isOpened); hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024, L"mmapFile"); if (hMapFile == NULL) { std::cout << "CreateFileMapping() Error: " << GetLastError() << "n"; return GetLastError(); } hEvent = CreateEvent(NULL, true, false, L"mmapEvent"); if (hEvent == INVALID_HANDLE_VALUE || hEvent == NULL) { std::cout << "CreateEvent() Error: " << GetLastError() << "n"; return GetLastError(); } char* buff = (char*)MapViewOfFile(hMapFile, FILE_MAP_WRITE, 0, 0, 0); if (!buff) { std::cout << "MapViewOfFile() Error: " << GetLastError() << "n"; return GetLastError(); } while (buff[0] != L'.') { std::cin >> buff; SetEvent(hEvent); } UnmapViewOfFile(buff); } else if (wcscmp(argv[1], L"r") == 0) { if (WaitForSingleObject(isOpened, 0) == WAIT_TIMEOUT) { std::cout << "Waiting for `win32mmap w`..."; WaitForSingleObject(isOpened, INFINITE); std::cout << "n"; } hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, L"mmapFile"); if (hMapFile == NULL) { std::cout << "CreateFileMapping() Error: " << GetLastError() << "n"; return GetLastError(); } hEvent = OpenEvent(EVENT_ALL_ACCESS, false, L"mmapEvent"); if (hEvent == INVALID_HANDLE_VALUE || hEvent == NULL) { std::cout << "CreateFile() Error: " << GetLastError() << "n"; return GetLastError(); } char* buff = (char*)MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0); if (!buff) { std::cout << "MapViewOfFile() Error: " << GetLastError() << "n"; return GetLastError(); } if (!buff) { std::cout << "MapViewOfFile() Error: " << GetLastError() << "n"; return GetLastError(); } while (true) { WaitForSingleObject(hEvent, INFINITE); ResetEvent(hEvent); if (buff[0] == '.') { break; } std::cout << buff << "n"; } UnmapViewOfFile(buff); } else { std::cout << "Usage: `win32mmap w` for writing, or `win32mmap r` for reading.n"; return -1; } CloseHandle(hMapFile); return 0; }
The program is a simple inter-process communication "chat" that relies on memory-mapped files. To use the program, you need to make two executable instance of the program:
win32mmap w
win32mmap r
.
My problem is when I run the 2 instances of the program, and I type the world
Hello
win32mmap w
Hello
Hello World
World
Hello World
Anonymous Changed status to publish May 14, 2021
Recent Comments