Its obvious that we have a code block like
int
main()
{
pid_t pid;
int y = 3;
if ( (pid = fork()) <0 )
return -1;;
if( pid == 0 ) /* child */
{
printf(" before: %d %p\n", y, &y );
y *= 10;
printf("after: %d %p\n", y, &y );
}
else /* father */
{
sleep(1);
printf("father: %d %p\n" , y , &y );
}
return 0;
}
The address printed is same for each printf() and as the the previous post on this topic suggests that its because of virtual memory.But my confusion is that does this imply that each parent and child possess separate physical address space and if yes then why can’t the virtual address be different as ultimately it will be mapped to corresponding physical address space by MMU.
Yes, each separate process possesses its own part of physical memory, even though the virtual addresses may collide, and even though optimisation techniques like copy-on-write are often performed.
Most modern implementations use copy-on-write which means that until one of the processes attempts to modify a piece of memory, both processes will refer to the same piece of physical memory.
In your particular case it implies that
yshould refer to the same chunk of physical memory in both processes before the child modifies it by multiplying it. At that point the kernel would copy the whole page whereyresides so that the two processes now refer to a different chunk of physical memory.