7
votes

I am confused about it. I have read that when a child is created by a parent process, child gets a copy of its parent's address space. What it means here by copy? If i use code below, then it prints same addresses of variable 'a' which is on heap in all cases. i.e in case of 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); }

}

5
Note that in both parent and child you do NOT print the address of variable a. You print the value of the variable a, (which is of type pointer).Didier Trosset
Did you see an answer you liked?Robert S. Barnes

5 Answers

25
votes

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 it's 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?

3
votes

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).

3
votes

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.

2
votes

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.

2
votes

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.