Search code examples
clinuxfork

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");
                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);
        }
}

Solution

  • 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?