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?
What fork() does is the following: It creates a new process which is a copy of the calling process. That means that it copies the caller's memory (code, globals, heap and stack), registers, and open files.
However, in the case of threads the address space will not be copied: the two threads will share the same memory, so if one thread modify a variable, it will impact all other threads.
When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. But this is not needed in certain cases. Consider the case when a child executes an "exec" system call or exits very soon after the fork().
all kind of data pointers, memory, variable will be duplicate in a separate memory for the child process created with fork.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With