What does mmap do?

What does this line of code do?

mmap(NULL, n, PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); 
+8
c ubuntu mmap
source share
2 answers

It requests a private, writable anonymous mapping of n bytes of memory.

  • A closed display means that it is not shared with other processes (for example, after fork() child and parent elements will have independent mappings);
  • Anonymous mapping means that it is not supported by the file.

In this case, it essentially requests a block of n bytes of memory, which is roughly equivalent to malloc(n) (although it needs to be freed using munmap() and not free() , and it will be page aligned). It also requests that the memory be writable, but does not request that it be readable, however, writable and unreadable memory is usually not a combination supported by the underlying hardware. When PROT_WRITE only PROT_WRITE , POSIX allows the implementation to provide memory that can also be read and / or executed.

+10
source share

man mmap will help you here.

It creates a memory mapping in the virtual address space of the process. This creates an anonymous mapping, which is more like using malloc to allocate n bytes of memory.

Options:

  • NULL - the kernel will select the address to display
  • n - display length (in bytes)
  • PROT_WRITE - pages can be written
  • MAP_ANON | MAP_PRIVATE MAP_ANON | MAP_PRIVATE - mapping is not supported by the file, and updates written to the mapping are private to the process
  • -1 - file descriptor; not used because display is not supported by file
  • 0 - the offset in the file in which the comparison is started is again not used, since the mapping is not supported by the file
+8
source share

All Articles