Two processes sharing the same heap

I didn't understand anything about the processes generated by fork (). If I try code like this:

int main(int argc, char** argv)
{
    void* mem=malloc(100);
    pid_t pid=fork();
    printf("%p\n",mem);
}

      

Both processes print the same address. So they point to the same area of ​​memory on the heap? Isn't it dangerous? There may be a conflict. My book says that the values ​​on the stack are copied, but it doesn't talk about the heap.

+3


source to share


2 answers


Different processes are contained in separate virtual address spaces, so these memory addresses point to different memory locations.



As Kara Horvath shows, this is a little more complicated due to an optimization called copy-on-write , which basically allows you to have one copy for as long as a distinction needs to be made. This is implemented through page faults, and at the end of the same addresses in two separate virtual address spaces do not refer to the same memory location.

+5


source


The environment, resource limits, umask, controlling terminal, current working directory, root directory, signal masks and other process resources are duplicated from the parent to the forked child process.



0


source







All Articles