How do I use the mmap function in C language? – The Linux Tip

How do I use the mmap function in C language? – The Linux Tip

The mmap() operate is used for mapping between a course of deal with house and both information or units. When a file is mapped to a course of deal with house, the file will be accessed like an array in this system. This is without doubt one of the best methods to entry knowledge within the file and gives a seamless coding interface that’s pure for a knowledge construction that may be assessed with out he abstraction of studying and writing from information. On this article, we’re going to focus on learn how to use the mmap() operate in Linux. So, let’s get began.

Header File:

Syntax:

void * mmap (void *deal with, size_t size, int defend, int flags, int filedes,
off_t offset)

Arguments:

The operate takes 6 arguments:

1. deal with:

This argument offers a most popular beginning deal with for the mapping. If one other mapping doesn’t exist there, then the kernel will decide a close-by web page boundary and create the mapping; in any other case, the kernel picks a brand new deal with. If this argument is NULL, then the kernel can place the mapping wherever it sees match.

2. size:

That is the variety of bytes which to be mapped.

3. defend:

This argument is used to regulate what sort of entry is permitted. This argument could also be logical ‘OR’ of the next flags PROT_READ | PROT_WRITE | PROT_EXEC | PROT_NONE.  The entry forms of learn, write and execute are the permissions on the content material.

4. flags:

This argument is used to regulate the character of the map. Following are some widespread values of the flags:

  • MAP_SHARED: This flag is used to share the mapping with all different processes, that are mapped to this object. Adjustments made to the mapping area can be written again to the file.
  • MAP_PRIVATE: When this flag is used, the mapping is not going to be seen by every other processes, and the modifications made is not going to be written to the file.
  • MAP_ANONYMOUS / MAP_ANON: This flag is used to create an nameless mapping. Nameless mapping means the mapping just isn’t linked to any information. This mapping is used as the fundamental primitive to increase the heap.
  • MAP_FIXED: When this flag is used, the system must be compelled to make use of the precise mapping deal with specified within the deal with If this isn’t doable, then the mapping can be failed.

5. filedes:

That is the file descriptor which must be mapped.

6. offset:

That is offset from the place the file mapping began. In easy phrases, the mapping connects to (offset) to (offset+length-1) bytes for the file open on filedes descriptor.

Return values:

On success, the mmap() returns 0; for failure, the operate returns MAP_FAILED.

Pictorially, we will signify the map operate as follows:

How do I use the mmap function in C language? – The Linux Tip

For unmap the mapped area munmap() operate is used :

Syntax:

int munmap(void *deal with, size_t size);

Return values:

On success, the munmap() returns 0; for failure, the operate returns -1.

Examples:

Now we’ll see an instance program for every of the next utilizing mmap() system name:

  • Reminiscence allocation (Example1.c)
  • Studying file (Example2.c)
  • Writing file (Example3.c)
  • Interprocess communication (Example4.c)

Example1.c

#embody
#embody

int foremost(){

int N=5; // Variety of parts for the array
int *ptr = mmap ( NULL, N*sizeof(int),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
0, 0 );
if(ptr == MAP_FAILED){
printf(“Mapping Failedn”);
return 1;
}

// Fill the weather of the array
for(int i=0; i “);
for(int i=0; i<N; i++){
printf(“[%d] “,ptr[i]);
}

printf(“n”);
int err = munmap(ptr, 10*sizeof(int));

if(err != 0){
printf(“UnMapping Failedn”);
return 1;
}
return 0;
}

How do I use the mmap function in C language? – The Linux Tip

In Example1.c we allocate reminiscence utilizing mmap. Right here we used PROT_READ | PROT_WRITE safety for studying and writing to the mapped area. We used the MAP_PRIVATE | MAP_ANONYMOUS flag. MAP_PRIVATE is used as a result of the mapping area just isn’t shared with different processes, and MAP_ANONYMOUS is used as a result of right here, we’ve got not mapped any file. For a similar cause, the file descriptor and the offset worth is about to 0.

Example2.c

#embody
#embody
#embody
#embody
#embody
#embody

int foremost(int argc, char *argv[]){

if(argc < 2){
printf(“File path not mentionedn”);
exit(0);
}

const char *filepath = argv[1];
int fd = open(filepath, O_RDONLY);
if(fd < 0)

struct stat statbuf;
int err = fstat(fd, &statbuf);
if(err < 0)

char *ptr = mmap(NULL,statbuf.st_size,
PROT_READ|PROT_WRITE,MAP_SHARED,
fd,0);
if(ptr == MAP_FAILED){
printf(“Mapping Failedn”);
return 1;
}
shut(fd);

ssize_t n = write(1,ptr,statbuf.st_size);
if(n != statbuf.st_size){
printf(“Write failed”);
}

err = munmap(ptr, statbuf.st_size);

if(err != 0){
printf(“UnMapping Failedn”);
return 1;
}
return 0;
}

How do I use the mmap function in C language? – The Linux Tip

In Example2.c we’ve got mapped the file “file1.txt”. First, we’ve got created the file, then mapped the file with the method. We open the file in O_RDONLY mode as a result of right here, we solely need to learn the file.

Example3.c

#embody
#embody
#embody
#embody
#embody
#embody

int foremost(int argc, char *argv[]){

if(argc < 2){
printf(“File path not mentionedn”);
exit(0);
}

const char *filepath = argv[1];
int fd = open(filepath, O_RDWR);
if(fd < 0)

struct stat statbuf;
int err = fstat(fd, &statbuf);
if(err < 0)

char *ptr = mmap(NULL,statbuf.st_size,
PROT_READ|PROT_WRITE,
MAP_SHARED,
fd,0);
if(ptr == MAP_FAILED){
printf(“Mapping Failedn”);
return 1;
}
shut(fd);

ssize_t n = write(1,ptr,statbuf.st_size);
if(n != statbuf.st_size){
printf(“Write failedn”);
}

// Reverse the file contents
for(size_t i=0; i n”);
n = write(1,ptr,statbuf.st_size);
if(n != statbuf.st_size){
printf(“Write failedn”);
}

err = munmap(ptr, statbuf.st_size);

if(err != 0){
printf(“UnMapping Failedn”);
return 1;
}
return 0;
}

How do I use the mmap function in C language? – The Linux Tip

In Example3.c we’ve got learn after which write to the file.

Example4.c

#embody
#embody
#embody
#embody

int foremost(){

int N=5; // Variety of parts for the array

int *ptr = mmap(NULL,N*sizeof(int),
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS,
0,0);

if(ptr == MAP_FAILED){
printf(“Mapping Failedn”);
return 1;
}

for(int i=0; i < N; i++){
ptr[i] = i + 1;
}

printf(“Preliminary values of the array parts :n”);
for (int i = 0; i < N; i++ ){
printf(” %d”, ptr[i] );
}
printf(“n”);

pid_t child_pid = fork();

if ( child_pid == 0 ){
//little one
for (int i = 0; i < N; i++){
ptr[i] = ptr[i] * 10;
}
}
else{
//mum or dad
waitpid ( child_pid, NULL, 0);
printf(“nParent:n”);

printf(“Up to date values of the array parts :n”);
for (int i = 0; i < N; i++ ){
printf(” %d”, ptr[i] );
}
printf(“n”);
}

int err = munmap(ptr, N*sizeof(int));

if(err != 0){
printf(“UnMapping Failedn”);
return 1;
}
return 0;
}

How do I use the mmap function in C language? – The Linux Tip

In Example4.c first the array is initialized with some values, then the kid course of updates the values. The mum or dad course of reads the values up to date by the kid as a result of the mapped reminiscence is shared by each processes.

Conclusion:

The mmap() is a robust system name. This operate shouldn’t be used when there are portability points as a result of this operate is barely supported by the Linux atmosphere.

mmap example in c,mmap c,mmap geeksforgeeks,how does mmap work,mmap vs malloc,mmap explained,what does mmap do