-   Linux - Kernel (
-   -   linux process memory sharing. ( 12-31-2012 10:15 PM

linux process memory sharing.
when we are creating child process,parent's data segment is copied for child.then why address of variable in both processes remains same even if i am changing variable in child process ? what is the logic behind it....?

theNbomr 12-31-2012 11:03 PM

Memory addresses seen by userspace processes are virtual addresses. The CPU's Memory Management Unit (MMU) translates these virtual addresses to physical addresses. The physical addresses are distinct, while the virtual addresses are common to all userspace processes. This is all part of protected memory CPU behavior.

--- rod.

Mara 01-01-2013 04:01 PM

Linux uses MMU in an advanced way. For instance, it uses copy-on-write mechanism, so it shared the physical page between processes if nobody is modifying it. It may, or may not, use the same virtual addresses (it also depends on the kernel settings like the heap randomization). However, the same virtual address in user space does not always mean the same physical page.

sundialsvcs 01-02-2013 11:19 AM

When a process forks, the page-tables of the new process are set to trigger a protection-fault when the page is modified ... causing a new shared copy of the page with identical content to be created for both processes ("copy on write," i.e. it is an "on-demand" action). The modification only occurs for the now-unique page copy owned by the one process that attempted it.

"And as for any dogs that are simply sleeping in the sun ... let them lie ... until and unless they wake up."

If you want to share memory between two or more processes, you can do so, e.g. with the shmget() call and its related brethren. This causes page-table entries to be allocated which are truly shared between the various processes: the pages in question (conceptually ...) have a "reference count" equal to the number of processes that share them. All of them can both read and write to the (one...) shared page, therefore all processes instantly perceive the change.

Note, however, that shared memory is a comparatively expensive resource, if only in the sense of being a much bigger elephant in the room.

Best practice, in my opinion, is to select an off-the-shelf, pre-existing, "soup to nuts" IPC (inter-process communication) scheme which manages all of the shared-memory stuff, all of the necessary semaphores and locking and such, for you. (Don't overlook good ol' pipes!) This is a programming requirement that has been tackled and solved hundreds of thousands of times before you. "Actum Ne Agas: Do Not Do A Thing Already Done."

All times are GMT -5. The time now is 12:36 PM.