Memory-mapped I/O lets us map a file on disk into a buffer in memory so that, when we fetch bytes from the buffer, the corresponding bytes of the file are read. Similarly, when we store data in the buffer, the corresponding bytes are automatically written to the file. This lets us perform I/O without using read or write.
#include <sys/mman.h> void *mmap(void *addr, size_t len, int prot, int flag, int fd, off_t off ); Returns: starting address of mapped region if OK, MAP_FAILED on error
The addr argument lets us specify the address where we want the mapped region to start. We normally set this value to 0 to allow the system to choose the starting address. The return value of this function is the starting address of the mapped area.
The fd argument is the file descriptor specifying the file that is to be mapped. We have to open this file before we can map it into the address space. The len argument is the number of bytes to map, and off is the starting offset in the file of the bytes to map.
The prot argument specifies the protection of the mapped region.
prot Description PROT_READ Region can be read. PROT_WRITE Region can be written. PROT_EXEC Region can be executed. PROT_NONE Region cannot be accessed.
- Advanced Programming in the UNIX Environment