4

Can a child process access(read and write) parent process's heap address space? Following is the program i tried at http://www.ideone.com/R5vDT which is running successfully:

int main(){
        int *p = (int*)malloc(sizeof(int));
        if(fork()){
        //parent process
                *p = 25;//Write
                printf("Parent %d: %d %p\n", getpid(), *p, p);//Read
        }else{
        //child process
                *p = 15;//write
                printf("Child %d: %d %p\n", getpid(), *p, p);//read
        }
        return 0;
}     

Output is:

Parent 30597: 25 0x9781008
Child 30600: 15 0x9781008

I have read about C-O-W (copy on write) but addresses pointed by p are same even after write operation. Should NOT the Operating System raise an exception because one process is accessing memory outside it's address space?

monish001
  • 671
  • 2
  • 8
  • 20

1 Answers1

7

Well, the two processes have their own address spaces that to each of the process looks the same, even though they are not accessing the same memory. However, many operating systems implement something called copy-on-write, meaning that the memory isn't copied at the time you call fork but rather when one of the processes modifies the memory. As long as no process is writing to the memory, they are reading from the same memory. When one of them tries to modify the memory, some type of exceptions is raised and the memory is copied so that they both have a private area of memory, inaccessible to any other process.

torgny
  • 176
  • 4
  • As in the program above, write operation has been performed by each of parent and child process. Should not the heap section be copied? Here are the program showing address of memory after write operation: http://www.ideone.com/nRa9a – monish001 Oct 25 '11 at 04:31
  • As i pointed out, the address space _looks_ the same to both the processes. Hence, both of them have access to an address 0x9781008. However, this is not the same physical location, so when one process modifies the content of that location, the content of that very same location of the other process is unchanged. You can try this by modifying the content of the address in one process and then, after it has been modified, print the content of the location in the other process. Whether your os implements COW is in fact irrelevant to your program. That is just a matter of _when_ the copy occurs. – torgny Oct 25 '11 at 07:27