Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mmap() Segmentation Fault Error While Reading The Stored Valued

I’m writing a program in C and using mmap() for processes to return the calculation to their main process.

Here is the code:

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

for (i = 0; i < count; i++)
   {
      pid_t pid = fork();
      if (pid == 0)
      {
         /// some calculations in the child.
         }
         
         // I save the result to ith element of mmap
         results[i] = calculation;
      }
      else{
         wait(NULL);
      }
      
   }
    
   // The following part arises an error called segmentation fault.
    for (i = 0; i < count; i++)
   {
      printf(" results[%d] = %d.\n", i, results[i]);
   }

When I try to access the results, I get an error. How can I fix that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help is appreciated.

>Solution :

To cite man mmap:

MAP_ANONYMOUS

The mapping is not backed by any file; its contents are initialized to zero. The fd argument is ignored; however, some implementations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading