kwsy
kwsy

Reputation: 39

python copy on write,realy?

when a process fork a child,the child will not copy father's variable but if the child process change the value of father's variable,it will create a new variable ,we call this copy on write,now please seet code below:

# coding=utf-8
import os
value = []
res = os.fork()

if res == 0:
    value = [324]
    print 'child  id={id} value={value}'.format(id=id(value), value=value)
else:
    value = [2]
    print 'parent  id={id} value={value}'.format(id=id(value), value=value)

if you run it ,the result maybe like this:

parent  id=4321407056 value=[2]
child  id=4321407056 value=[324]

my question is :

(1) the memory address of variable value is same ,it is 4321407056. but I have changed the value,that means I write the new value to the variable,why not the memory address is not changed?

(2) if they have the same memory address,why they have the different value,one is [2],the other is [234]?

Upvotes: 3

Views: 391

Answers (1)

viraptor
viraptor

Reputation: 34155

They're different processes. Since every modern system now uses virtual memory, the address you see in the application doesn't really correspond to where the information is physically stored. The same address could be for different applications: somewhere in the heap, mapped to a disk file, mapped to display device, not existent or something completely different.

When process forks, it will keep the parent's logical memory map - otherwise all the pointers would need updating. But the map will point at completely different physical memory region after a change is made.

Upvotes: 2

Related Questions