Is access to heap section of parent process by child process (created by fork() ) legal?

2.5k views Asked by At

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?

1

There are 1 answers

2
torgny On BEST ANSWER

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.