Let me try to address part of this question, specifically:
But these kinds of code where fd is set to -1 are frequent. What does it mean, what are the advantages of doing so.?
mmap()
is used for creating a memory mapping somewhere in virtual memory (somewhere which can be referenced to by the process issuing mmap). Specifying a file descriptor allows the memory to be swapped out to disk. Also, as only the region of the file currently accessed has to be loaded to memory, one can mmap files of size consistently larger than physical memory and disk (swap) space. See the GNU documentation.
There are several use cases where one would want to not specify a file descriptor and map an anonymous region of memory. One of them could be to extend a process' heap. Another would be the will to share data without having them persisted in a file, and thus not incur extra I/O overhead. From the GNU doc again:
MAP_ANONYMOUS
MAP_ANON
This flag tells the system to create an anonymous mapping, not connected to a file. filedes and offset are ignored, and the region is initialized with zeros.
Anonymous maps are used as the basic primitive to extend the heap on some systems. They are also useful to share data between multiple tasks without creating a file.
On some systems using private anonymous mmaps is more efficient than using malloc for large blocks. This is not an issue with the GNU C Library, as the included malloc automatically uses mmap where
appropriate.
However, note that anonymous mmap-ed memory can only be accessed from within the process, or by its child(ren). Since the memory is anonymous, there is no way to reference it! One would have to use shm_open()
to wrap the shared memory in an object and make it available to other processes. See that excerpt from the shm_open()
man page (bolded part is mine):
shm_open() creates and opens a new, or opens an existing, POSIX shared memory object. A POSIX shared memory object is in effect a handle which can be used by unrelated processes to mmap(2) the same region of shared memory
fd = -1
is just compliance for some systems to accept your allocation and disregard the file descriptor. See that expert from man mmap on Linux:
MAP_ANONYMOUS
The mapping is not backed by any file; its contents are initialized to zero. The fd and offset argument are ignored; however, some implementations require fd to be -1 if MAP_ANONYMOUS (or
MAP_ANON) is specified, and portable applications should ensure this. The use of MAP_ANONYMOUS in
conjunction with MAP_SHARED is supported on Linux only since kernel 2.4.
One of the question you mention has some reference about this system specific behavior.