Difference between the address space of a parent process and its child process in Linux?

I am confused by this. I read that when a child is created by the parent process, child gets a copy of the parent address space. What does that mean, copy? If I use the code below, then it prints the same addresses of the variable 'a', which is on the heap in all cases. that is, in the case of the child and the parent. So what's going on here?

int main () {pid_t pid; int * a = (int *) malloc (4); printf ("heap pointer% p \ n", a); pid = fork (); if (pid <0) {fprintf (stderr, "Fork Failed"); Output (-1); } else if (pid == 0) {printf ("Child \ n"); printf ("in the child heap pointer% p \ n", a); } else {

wait (NULL); printf ("Child Complete\n"); printf ("in parent heap pointer %p\n", a); exit(0); }

}

+4
source share
5 answers

The child receives an exact copy of the address space of the parents, which in many cases can be laid out in the same format as the parent address space. I must point out that each of them will have its own virtual address space for its memory, so that everyone can have the same data at the same address, but in different address spaces. In addition, linux uses a copy when writing when creating child processes. This means that the parent and child will share the parent address space until one of them writes, and at this point the memory will be physically copied to the child. This eliminates unnecessary copies during the exec new process. Since you are simply overwriting memory with a new executable file, why copy it?

+13
source

A copy means that it is a bit-identical copy of the virtual address space. In all senses and purposes, these two copies are indistinguishable until you start writing on one (the changes are not visible in the other copy).

+1
source

You get two heaps, and since memory addresses translate to different parts of physical memory, they both have the same virtual memory address.

+1
source

With fork() child process receives a new address space in which the entire contents of the parent address space are copied (in fact, modern kernels use copy-on-write).

This means that if you change a or the value specified by it in the process, the other process still sees the old value.

0
source

Yes, you will get the same virtual address, but remember that each of them has its own virtual address spaces of the process. Until the copy operation is performed while recording, everything will be common. Therefore, when you try to perform a strcpy operation or any write operation, write-by-copy occurs, which means that the child process of the virtual address of pointer a will be updated for the child process, but not so for the parent process.

0
source

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


All Articles