- 1 year ago
windows - plain shared memory between 2 processes (no file mapping, no pipe, no other extra)
In Windows, you can create a shared memory region between two processes without using file mapping, pipes, or any other extra mechanisms by using the following steps:
Create Shared Memory Region in One Process:
In one of the processes, use the Windows API functionCreateFileMapping
to create a shared memory region. This function creates or opens a named shared memory object that can be accessed by other processes.c#include <Windows.h>
int main() {
// Create a named shared memory region
HANDLE hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // Use INVALID_HANDLE_VALUE to create a new object
NULL, // Security attributes (use default)
PAGE_READWRITE, // Read/write access
0, // High-order 32 bits of object size (if 0, the size is specified by dwMaximumSizeHigh and dwMaximumSizeLow)
4096, // Low-order 32 bits of object size (size of shared memory in bytes, here set to 4096 bytes)
L"MySharedMemory"); // Name of the shared memory region (must be unique)
if (hMapFile == NULL) {
// Error handling
return 1;
}
// Continue using the shared memory region as needed...
CloseHandle(hMapFile); // Don't forget to close the handle when done
return 0;
}
Access the Shared Memory Region in Another Process:
In the second process, open the shared memory region created by the first process using the same name provided in theCreateFileMapping
call.c#include <Windows.h>
int main() {
// Open the named shared memory region
HANDLE hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // Access rights
FALSE, // Inheritable flag
L"MySharedMemory"); // Name of the shared memory region (same name used in the first process)
if (hMapFile == NULL) {
// Error handling
return 1;
}
// Map the shared memory region into the process's address space
LPVOID pView = MapViewOfFile(
hMapFile, // Handle to the mapped object
FILE_MAP_ALL_ACCESS, // Access rights
0, // High-order 32 bits of the file offset
0, // Low-order 32 bits of the file offset
4096 // Number of bytes to map (size of shared memory)
);
if (pView == NULL) {
// Error handling
CloseHandle(hMapFile);
return 1;
}
// Continue using the shared memory region through the pointer pView...
UnmapViewOfFile(pView); // Unmap the view when done
CloseHandle(hMapFile); // Close the handle when done
return 0;
}
In this approach, two processes can communicate by reading and writing to the shared memory region without the need for any extra communication mechanisms like pipes or files. However, you need to be cautious when using shared memory to ensure proper synchronization between processes to avoid data corruption or race conditions. Consider using synchronization mechanisms like mutexes or semaphores to coordinate access to the shared memory region between the processes.