After the child process is created, it runs on parent's address space until exec or exit is called. This means, both child and parent share the same address space until exec or exit is called.
vfork() also guarantees that after forking, child will be the first one to run until exec or exit is called. While the child process is running, before calling exec or exit, parent process will not run. Parent process will resume only when exec or exit is called by the child process.
Below given is a simple example, which will help you to understand the difference between them.
Compile and execute the following program
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pid,var=1;
if((pid=vfork())==0)
{
// Child process starts
var=var+1;
exit(0);
// Child process ends
}
// Parent process continues
printf("value of var %d",var);
return 0;
}
Note the value of var. The output will be
value of var 2.
As we can see, the value of var in parent's address space has been changed by the child process. This means, no other address space was created for child, unless exec was called.
Now run the same program using fork() instead of vfork(), and the output will be
value of var 1.
This is because, we are changing var in child's address space, so value in parent's address space will not change.
Nice explanation
ReplyDelete