Re: Basic Fork Question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello...

> Process A has a memory allocated and memory pointer x pointing to
> that memory. I fork process B from a running process A.B gets a new
> copy of the memory and the pointer.However, printing x in A and B
> points to the same memory location(though actually differnt physical
> memory locations).What is the concept of VM here.Can anyone kindly
> explain ?

First, strace is your friend here :) use it to find out how fork() is 
eventually transformed into clone(). You will watch that there is no 
CLONE_VM there, so child is actually given a separate address 
space...but initially they are pointing to the same pages. Only when 
one of them is writing something to these pages (stack, heap, etc), 
Copy on Write is triggered, thus the writer is assigned unique pages.

In your case, actually they are pointing to different location of 
physical memory. But remember, we "live" under the mercy of virtual 
memory manager. Even though pointer a points to different physical 
address, virtual memory manager is able to manipulate the page table 
thus it points to identical virtual memory address.

More specifically, a is variable which lives in stack area. Stack area, 
especially in non randomized address space enabled-kernel, always start 
more or less in same virtual address. So, even you fork a child, kernel 
tends to assign same virtual memory address for stack pointer. When a 
local variable is allocated, stack pointer is decremented (in 
architecture where stack grows to the lower address) with the same 
number, there's why you got same output on both child and parent.

Observe the assembly instruction of your fork test program and you will 
get better understanding. Usually, this code block:
<snip>
void main()
{
        char a=0;
<snip>

will be transformed into this:
 804835c:    55               push   %ebp
 804835d:    89 e5         mov    %esp,%ebp
 804835f:     83 ec 08    sub    $0x8,%esp --> allocating "a"
 8048362:    83 e4 f0     and    $0xfffffff0,%esp --> aligning "a"
 8048365:    b8 00 00 00 00   mov    $0x0,%eax
 804836a:    29 c4                   sub    %eax,%esp

Got the picture now? If stack VMA starts from same virtual address, "a" 
as result of decrementing %sp, will end in same virtual address too.

Pheww, this is a bit tricky for me. I hope I can explain in very clearly 
in one shot :)

regards,

Mulyadi


--
Kernelnewbies: Help each other learn about the Linux kernel.
Archive:       http://mail.nl.linux.org/kernelnewbies/
FAQ:           http://kernelnewbies.org/faq/


[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux