[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Shared mappings not being inherited by children
From: |
Agustina Arzille |
Subject: |
Shared mappings not being inherited by children |
Date: |
Sat, 02 Apr 2016 13:35:49 -0300 |
Hello, everyone.
It appears that memory mappings obtained by 'mmap' with MAP_SHARED
and MAP_ANON as its flags are not being inherited by children processes.
Here's a simple program that illustrates the issue:
===============================
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/wait.h>
int main (void)
{
void *p = mmap (0, 4096, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANON, -1, 0);
if (p == MAP_FAILED)
{
puts ("mmap failed.");
return (1);
}
int pid = fork ();
if (pid < 0)
{
puts ("fork failed.");
return (1);
}
else if (pid == 0)
{
*(int *)p = 69;
puts ("value was set.");
}
else
{
int r;
wait (&r);
printf ("done waiting for the child"
"\nvalue is: %d\n", *(int *)p);
}
return (0);
}
==================================
The parent process ends up printing zero, which is wrong, of course.
Strangely enough, setting the protection to RWX seems to make it work.
Another alternative is to call 'vm_inherit' to specifiy a shared mapping
prior to doing the fork.
A quick inspection at the source code tells me that this code ends up calling
'vm_allocate' as an optimization when it sees that the user requested an
anonymous mapping with protection RW. However, it's not taking into account
that 'vm_allocate' has a default inheritance value of 'COPY'.
As a workaround, we could always use 'vm_map', no matter what, since the
idea that 'vm_allocate' has a little less overhead is somewhat bogus to me, or
keep using 'vm_allocate', but do an additional 'vm_inherit' if the user
specified
a shared mapping.
What do you guys think?
Re: Shared mappings not being inherited by children, Samuel Thibault, 2016/04/04