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;
}
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
&ais mapped to some physical address. Fork initially just copies the mapping. Then, when the processes write toa, CoW kicks in and in the child process, the physical page that holdsais copied, the virtual address mapping is updated to refer to the copy and both processes have their own copy ofa, at the same virtual address&abut at different physical addresses.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%pinstead. Also, the return type offorkispid_t, notint.]