Parent and Child address space confusion

Its obvious that we have a code block like

  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 */
   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 y should 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 where y resides so that the two processes now refer to a different chunk of physical memory.

Because then you would have to adjust every single pointer for no useful reason. Since the program is the same for each process, they have to use the same virtual addresses to work. Of course even virtual addresses will likely be different when using dynamic allocation.

What you print here with &y are the virtual addresses. They can be different, but it makes sense that for a forked child process they are the same that in the parent process.

But on the other side, the physical addresses are different for the parent and the child. That's why the values are still the same, even after the multiplication.

Need Your Help

How to stop NotificationListenerService android?

android service notifications listener

I'm using a NotificationListenerService in my android app that was developed from kpbird's example. The service runs in the background even after the app is destroyed. Is there a way to stop this