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?
Any help is appreciated.
CodePudding user response:
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.