Memory mapping

By Danny Kalev, ITworld |  How-to

Offset 0 indicates mapping from the
file's beginning.

In the following example, the program maps the first 4 KB of a file
passed whose name is passed as a command line argument:

#include
#include
#include
#include

int main(int argc, char *argv[])
{
int fd;
void * pregion;
if (fd= open(argv[1], O_RDONLY) <0)
{
perror("failed on open");
return -1;
}
/*map first 4 kilobytes of fd*/
pregion=mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
if (pregion==(caddr_t)-1)
{
perror("mmap failed")
return -1;
}
close(fd);
/*..access mapped memory*/
}

The munmap() function unmaps a mapped region.

int munmap(caddr_t addr, int length);

addr is the regions address and length specifies how much of the memory
should be unmapped (you may unmap a portion of a mapped region).

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question