Reputation: 171
I've been googling this a little bit and haven't been able to find a clear answer so I'm hoping someone has some insight into shared memory segments in windows VS linux.
In Linux there are 2 ways of creating shared memory for IPC: shared memory segments (shmget, et al) and memory mapped files (mmap). From my brief understanding mmap requires you to have an actual file somewhere in the OS to map whereas shared memory segments are just name based segments in memory that can be attached to by processes.
In Windows there only seems to be the equivalent of memory mapped files where you have to have an actual file floating around somewhere.
My question: Is this actually the only kind of shared memory in Windows or does it have an api for creating non file based shared memory segments.
Upvotes: 10
Views: 8346
Reputation: 181
This might be a bit late.
The biggest difference is the memory allocation granularity size. Linux is 4K and Windows is 64K. If it's important to have say arbitrary 8K pages mapped into specific 8K destinations well you are stuck on Windows and it just can't be done. (If someone figures this out then please let me know).
Another difference is you can mmap a new page over the top of an existing page effectively replacing the first page mapping. In windows you can't do this but instead must destroy the entire view and rebuild the entire view in what ever new layout that is required. So if the "view" contains 1024 pages and 1 page changes then in Linux you can just change that one page. In Windows you must drop all 1024 pages and re-view the same 1023 pages + the one new page!
http://nullprogram.com/blog/2016/04/10/
I've used this and it works.
Upvotes: 1
Reputation: 4677
Yes, you can use non file-based shared memory segments in Windows.
#pragma comment(linker, "/SECTION:.shared,RWS")
#pragma data_seg(".shared")
int g_iShared = 0;
#pragma data_seg()
Upvotes: 2
Reputation: 74485
The Unix mmap()
API is practically equivalent to the CreateFileMapping
/MapViewOfFile
Windows API. Both can map files and/or can create shared (anonymous) maps that are backed by the swap device (if any). As a matter of fact, glibc uses anonymous mmap()
to implement malloc()
when the requested memory size is sufficiently large.
Windows supports one additional mechanism - shared data sections in the executable file, something that is not implemented in Linux. First you create a named data section using the #pragma data_seg(".somename")
and put the shared variables inside. Then you tell the linker to mark the section as read/write/shared with the following option: /SECTION:.somename,RWS
. The whole process is described in MSDN. This only works for copies of the same module, either EXE or DLL file. Same module means same file in the same file system location: processes created from different copies of the same executable but located in different places won't see each others named sections as shared.
Upvotes: 8