Confusion of address space for parents and children

Obviously, 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 printable address is the same for each printf (), and the previous post in this section assumes that it is due to virtual memory. But my confusion is that this means that each parent and child have a separate physical address space, and if so, then why the virtual address cannot be different, because ultimately it will be mapped to the corresponding physical address space using the MMU .

+4
source share
3 answers

Yes, each individual process has its own part of physical memory, although virtual addresses may collide, even though optimization methods such as copy to write are often used.

Most modern implementations use copy-on-write, which means that until one of the processes tries to change part of the memory, both processes will refer to the same piece of physical memory.

In your particular case, this means that y must refer to the same piece of physical memory in both processes before the child modifies it by multiplying it. At this point, the kernel copies the entire page, where y is located so that the two processes now belong to another piece of physical memory.

+1
source

Because then you have to tune each pointer without any useful reason. Since each process has the same program, they must use the same virtual addresses to work. Of course, even when using dynamic allocation, even virtual addresses will be different.

+2
source

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

But on the other hand, physical addresses are different for the parent and for the child. Therefore, the values ​​remain unchanged even after multiplication.

0
source

Source: https://habr.com/ru/post/1384272/


All Articles