Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the memory is mapped when fork is used?

i am new to "fork()",I read everywhere that when a fork() is called an exact copy of current (calling) process is started.Now when I run following code ,there should be two different processes, having two different memory locations assigned to their vars and functions.

#include<stdio.h>
int i=10;
int pid;
 int main(){
  if((pid=fork())==0){
    i++;//somewhere I read that separate memory space for child is created when write is needed
    printf("parent address= %p\n",&i);// this should return the address from parent's memory space
  }else{
    i++;
    i++;
    printf("child address= %p\n",&i);// this should return the address of child's memory space 
  }
  wait(0);
  return(0);
 }
Why The output looks like:: 
child address::804a01c 
parent address::804a01c

Why both the address are the same for parent as well as child?

like image 978
buch11 Avatar asked Mar 15 '12 16:03

buch11


People also ask

Does a forked process share memory?

Answer: Only the shared memory segments are shared between the parent process and the newly forked child process. Copies of the stack and the heap are made for the newly created process.

How is memory mapping done?

Memory-mapping is a mechanism that maps a portion of a file, or an entire file, on disk to a range of addresses within an application's address space. The application can then access files on disk in the same way it accesses dynamic memory.

What is fork memory?

The fork operation creates a separate address space for the child. The child process has an exact copy of all the memory segments of the parent process.

Does fork double memory?

Save this answer. Show activity on this post. fork() duplicates the entire process. The only difference is in the return value of the fork() call itself -- in the parent it returns the child's PID, in the child it returns 0 .


1 Answers

having two different memory locations assigned to their vars and functions.

Nope; Linux implements virtual memory, meaning that each process has its own complete address space. As a result, after a fork, both processes see the same addresses for their copies of in-memory objects.

(As an aside: VM also causes code to be shared between the process in physical memory, and all data will only be copied-on-write.)

like image 94
Fred Foo Avatar answered Oct 03 '22 11:10

Fred Foo