开发者

Difference between the address space of parent process and its child process in Linux?

I am confused about something. I have read that when a child is created by a parent process, the child gets a copy of its parent's address space. What does it mean by copy? If I use the code below, then it prints the same value for variable 'a' which is on the heap in both tthe child and parent. So what is happening here?

int main ()
{
        pid_t pid;
        int *a = (int *)malloc(4);
        printf ("heap pointer %p\n", a);
        pid = fork();
        if (pid < 0) {
                fprintf (stderr, "Fork Failed");
                exit(-1);
        }
        else if (pid == 0) {
                printf ("Child\n"开发者_C百科;);
                printf ("in child heap pointer %p\n", a);
        }
        else {

                wait (NULL);
                printf ("Child Complete\n");
                printf ("in parent heap pointer %p\n", a);
                exit(0);
        }
}


The child gets an exact copy of the parents address space, which in many cases is likely to be laid out in the same format as the parent address space. I have to point out that each one will have it's own virtual address space for its memory, such that each could have the same data at the same address, yet in different address spaces. Also, Linux uses copy on write when creating child processes. This means that the parent and child will share the parent address space until one of them does a write, at which point the memory will be physically copied to the child. This eliminates unneeded copies when execing a new process. Since you're just going to overwrite the memory with a new executable, why bother copying it?


Yes, you will get the same virtual address, but remember each one has it's own process virtual address spaces. Till there is a Copy-On-Write operation done everything is shared. So when you try to strcpy or any write operation the Copy-On-Write takes place which means the child process virtual address of pointer a will be updated for the child process, but not so for the parent process.


A copy means exactly that, a bit-identical copy of the virtual address space. For all intents and purposes, the two copies are indistinguishable, until you start writing to one (the changes are not visible in the other copy).


With fork() the child process receives a new address space where all the contents of the parent address space are copied (actually, modern kernels use copy-on-write).

This means that if you modify a or the value pointed by it in a process, the other process still sees the old value.


You get two heaps, and since the memory addresses are translated to different parts of physical memory, both of them have the same virtual memory address.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜