tags:

views:

171

answers:

4
+5  A: 

You're right. As soon as you call fork(), two identical processes exist. Therefore, the address of y is the same for the copy of y in each process. The only difference between the two processes is that in one, fork() returned 0, and in the other it returned the PID of the child. Your program is using that information to do different behaviour in the parent and child, so you get the appropriate output.

In "real life", operating systems do a lot of optimizations to make fork() really fast. That means that the actual physical behaviour probably doesn't involve a complete copy of the memory space. Logically, however, you can treat it as such.

Carl Norum
but what about the the comment of "separate address spaces fro child and parent?"
Vijay Sarathi
@benjamin, yeah they're different processes, so each has it's own separate virtual memory space. They're completely independent as soon as `fork()` returns.
Carl Norum
"Seperate address spaces" means that a given address in one process refers to a seperate bit of memory from the same address in the other process. That's how address 69002894 in your example is able to store both `X` and `Y` at the same time - "address 69002894 in process A" is a distinct location from "address 69002894 in process B".
caf
+2  A: 

They have separate address space -- that is precisely why the same memory address is allowed to have different values. A memory address only has meaning in the context of a process.

Billy ONeal
+2  A: 

Address 221 P Street is a separate building from address 221 C Street. Their contents differ even though they have the same address number.

Windows programmer
+3  A: 

Hello Benjamin, Basically the concept of virtual memory gives a view to the process as if it is the sole owner of the system. It feels it has access to the complete memory.

But in reality, the OS gives it only a virtual memory which is mapped to the actual memory by the OS by using MMU.

So, what happens in your case is, each process (parent and child) have their own address space. And this is separate for both. Now here, the address space refers to the virtual address space.

So, though both in parent and child the same address is present, this is just the virtual address. and each maps to a different physical address.

Hope it helps!!

Furquan