i was just checking the behaviour of fork system call and i found it very confusing.
i saw in a website that
Unix will make an exact copy of the parent’s address space and give it to the child. Therefore, the parent and child processes have separate address spaces
#include <stdio.h>
#include <sys/types.h>
int main(void)
{
pid_t pid;
char y='Y';
char *ptr;
ptr=&y;
pid = fork();
if (pid == 0)
{
y='Z';
printf(" *** Child process ***\n");
printf(" Address is %p\n",ptr);
printf(" char value is %c\n",y);
sleep(5);
}
else
{
sleep(5);
printf("\n ***parent process ***\n",&y);
printf(" Address is %p\n",ptr);
printf(" char value is %c\n",y);
}
}
the output of the above program is :
*** Child process ***
Address is 69002894
char value is Z
***parent process ***
Address is 69002894
char value is Y
so from the above mentioned statement it seems that child and parent have separet address spaces.this is the reason why char value is printed separately and why am i seeing the address of the variable as same in both child and parent processes.?
Please help me understand this!
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!!