Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting parent and child behavior while doing fork

Can someone please explain the output of the program below . Why am i getting the same value of &a for both parent and child.

They must have the different physical address.If i consider that i am getting the virtual address then how can they have same virtual address because as far as i know each physical address is uniquely bound to virtual address.

#include <stdio.h>
#include <stdlib.h>
int main(void) {


    int pid=fork();
      int a=10;
    if(pid==0)
        {
            a=a+5;
            printf("%d %d\n",a,&a);
        }
        else
        {
            a=a-5;
            printf("%d %d\n",a,&a);
        }
        return 0;
}
like image 789
Devender Goyal Avatar asked Nov 16 '25 14:11

Devender Goyal


1 Answers

The child process inherits its virtual address space from the parent, even though the virtual addresses start referring to different physical addresses once the child writes to a page. That's called copy-on-write (CoW) semantics.

So, in the parent &a is mapped to some physical address. Fork initially just copies the mapping. Then, when the processes write to a, CoW kicks in and in the child process, the physical page that holds a is copied, the virtual address mapping is updated to refer to the copy and both processes have their own copy of a, at the same virtual address &a but at different physical addresses.

each physical address is uniquely bound to virtual address

That's not true. A physical memory address may be unmapped, or it may be mapped to multiple virtual addresses in one or more processes' address spaces.

Conversely, a single virtual address can be mapped to several physical address, as long as these virtual addresses exist in different processes' virtual address spaces.

[Btw., you can't reliably print memory addresses with %d (that just happens to work on 32-bit x86). Use %p instead. Also, the return type of fork is pid_t, not int.]

like image 186
Fred Foo Avatar answered Nov 19 '25 09:11

Fred Foo