Fork - same memory addresses?
This is about C in Linux.
I have fork()
in main()
where I create 2 child processes. Then, in both child process a run the function abc()
, where there is a local variable x
. I write some value in it. Then I print the address of this variable with printf("%p",&x)
.
Both processes print SAME address. I thought every child gets a (independent) copy of parent's memory. I need every process to have its own variable x
. How can I do that or am I doing something wrong?
You need to understand that there is a disconnect between physical memory and the virtual address space of a process.
Every single process gets its own 4G virtual address space and it's the job of the operating systems and hardware memory managers to map your virtual addresses to physical ones.
So, while it may seem that two processes have the same address for a variable, that's only the virtual address.
The memory manager will map that to a totally different physical addressa.
This mapping is also what allows you to run ten processes, each taking up 1G, even though your machine only has 4G of physical memory. The OS can swap bits of your memory out to disk and bring them back in when you try to use them.
a: Mostly, this is true. It may map to the same physical address if you're sharing stuff between processes. For example, shared memory, kernel code and data, dynamic libraries and so forth.
If you stop to think for a minute, it would be impossible for fork
to give variables separate addresses in the parent and child process. You could already have stored the addresses anywhere in memory, or hashed them, or saved them out to a file, or anything, and then anything in the child that depended on these addresses being valid would horribly break. In fact fork
does and must create a child process in which the virtual address space is identical to the virtual address space of the parent.
Because of the virtual memory system, each child processes have its own variable with the same (virtual) address.
The same virtual addresses won't point to the same physical location.