On Windows, there is a CreateFileMapping API which allows for creating a block of memory which may be backed by a file and MapViewOfFile which allows for mapping parts of the file, even the same parts to multiple virtual memory regions. Here's an example program
#include <windows.h>
#include <stdio.h>
int main() {
// Create a file mapping object for shared memory
HANDLE hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 256, L"MySharedMemory");
if (hMapFile == NULL) {
printf("Could not create file mapping object (%d).\n", GetLastError());
return 1;
}
// Map a view of the file mapping into the current process
LPVOID p1 = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 256);
if (p1 == NULL) {
printf("Could not map view of file (%d).\n", GetLastError());
CloseHandle(hMapFile);
return 1;
}
// Map another view of the same file mapping into the current process
LPVOID p2 = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 256);
if (p2 == NULL) {
printf("Could not map view of file (%d).\n", GetLastError());
UnmapViewOfFile(p1);
CloseHandle(hMapFile);
return 1;
}
// Use the memory regions via p1 and p2
strcpy((char*)p1, "Hello, world!");
printf("p2 sees: %s\n", (char*)p2);
// Clean up
UnmapViewOfFile(p1);
UnmapViewOfFile(p2);
CloseHandle(hMapFile);
return 0;
}
Is it possible to do this on Linux and macOS? What APIs would I need to use? It seems like mmap doesn't have a concept of a file handle for non-file backed mapped memory.