4

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.

Community
  • 1
  • 1
Gaurav B
  • 160
  • 8

3 Answers3

2

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.

Viruzzo
  • 3,025
  • 13
  • 13
1

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.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
  • Okay, so it suggests that till the execution of multiplication in child process, both child and parent is pointing to the same physical address and as the execution completes and ultimately value modifies then kernel copies every thing of original physical address space to new physical address and now virtual address of child map to that.But the similarity of virtual address spaces is merely for optimization? – Gaurav B Dec 02 '11 at 08:56
  • No, it's a necessity: the compiled program uses virtual memory addresses to access variables (and well, pretty much everything). These are determined at compile time. – Viruzzo Dec 02 '11 at 14:04
0

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.

Didier Trosset
  • 36,376
  • 13
  • 83
  • 122