What is mmap ?

MMAP

mmap (memory map) is for faster read/write of data from/to memory instead of files from disk.
If a process is terminated abruptly, memory data has to be saved to a file instead of being lost completely.

  • mmap() creates a mapping between a file and calling process’ address space.
  • A process can read (and also modify)

  #include <sys/mman.h>
  void* mmap(void *start, size_t length,
  int prot, int flags, int fd, off_t offset);
  start à address where to map the file, value 0 implies system to allocate
  length à number of bytes to map
  prot à protection required for the memory map
  flag à whether the map to be shared or private
  fd à descriptor of the file which is to be mapped
  offset à offset within the file, 0 implies beginning of the file
On success, returns a pointer to the memory map; otherwise returns NULL.
 


munmap()

  • This system call unmaps (deletes the mapping) for the calling process, for the specified address range.

  #include <sys/mman.h>
  int munmap(void *start, size_t length);
  start – the address returned by mmap()
  length – bytes to be unmapped

  • After this call, any access to the memory is invalid.
  • Memory map gets unmapped automatically, when the process terminates.
  • However, closing of the file descriptor does not trigger unmapping.

 


mmap() – example

#include <fcntl.h>
#include <sys/mman.h>
int main (int argc, char* argv[])
{
int fd;
void* filemap;
long  filesize;
fd = open (argv[1], O_RDONLY);
// TODO:  get file size saved into the variable filesize
filemap = mmap(0, filesize, PROT_READ, MAP_PRIVATE, fd, 0);
// map entire file
close (fd);  // file descriptor no longer needed
// TODO: use filemap to write the file content onto the screen
munmap (filemap, filesize);  // at the end unmap the file
}