tags:

views:

75

answers:

2
+3  Q: 

What does mmap do?

mmap(NULL, n, PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);

hi... i am trying to figure out the meaning of above code...?

+2  A: 

man mmap will help you here.

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

The parameters are:

  • NULL - the kernel will choose an address for the mapping
  • n - length of the mapping (in bytes)
  • PROT_WRITE - pages may be written
  • MAP_ANON | MAP_PRIVATE - mapping is not backed by a file, and updates written to the mapping are private to the process
  • -1 - the file descriptor; not used because the mapping is not backed by a file
  • 0 - offset within the file at which to start the mapping - again, not used, because the mapping is not backed by a file
Richard Fearn
+3  A: 

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

  • A private mapping means it's not shared with other processes (eg, after a fork() the child and parent will have independent mappings);
  • An anonymous mapping means that it's not backed by a file.

In this case, it is essentially requesting a block of n bytes of memory, so roughly equivalent to malloc(n) (although it must be freed with munmap() rather than free()). It's also requesting that the memory be writeable-but-not-readable, but such a request is typically not supported by the underlying hardware.

caf