ARBY ARBY - 7 months ago 43
C Question

new process created using fork but printing same address for variables

I have the code below:

int main()
int a=0;
printf("before: %d %p\n",a,&a);
int t=fork();
printf("child: %d %p\n",a,&a);
printf("parent: %d %p\n",a,&a);
//printf("both: %d %p\n",a,&a);
return 0;

Why all the addresses are printed same? I thought a new copy of the variables are created when fork is called. Does it have anything to do with virtual address and physical address? If so how the same virtual address gets mapped to different physical addresses?


The addresses are the same because each process (parent & child) has its own virtual address space. Linux computers have virtual memory (provided by the kernel & the processor).

The fork system call is "magically" copying the virtual address space of the parent process into the virtual address space of the child process (except for the result of fork). This copying uses lazy copy-on-write techniques so is quite efficient. The kernel is managing the MMU (used for virtual memory and to implement each virtual address space)

Read Advanced Linux Programming (it has several chapters related to that) & carefully fork(2).

BTW, take the habit of calling fflush(NULL); before fork. See fflush(3).