Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusing fork system call

Tags:

c++

c

fork

unix

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!

like image 276
Vijay Avatar asked Nov 29 '22 19:11

Vijay


2 Answers

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!!

like image 195
Furquan Avatar answered Dec 06 '22 09:12

Furquan


You're right. As soon as you call fork(), two identical processes exist. Therefore, the address of y is the same for the copy of y in each process. The only difference between the two processes is that in one, fork() returned 0, and in the other it returned the PID of the child. Your program is using that information to do different behaviour in the parent and child, so you get the appropriate output.

In "real life", operating systems do a lot of optimizations to make fork() really fast. That means that the actual physical behaviour probably doesn't involve a complete copy of the memory space. Logically, however, you can treat it as such.

like image 39
Carl Norum Avatar answered Dec 06 '22 09:12

Carl Norum