Considering the below code :
int main()
{
int pid;
pid=vfork();
if(pid==0)
printf("child\n");
else
printf("parent\n");
return 0;
}
In case of vfork() the adress space used by parent process and child process is same, so single copy of variable pid should be there. Now i cant understand how this pid variable can have two values returned by vfork() i.e. zero for child and non zero for parent ?
In case of fork() the adress space also gets copied and there are two copy of pid variable in each child and parent, so I can understand in this case two different copies can have different values returned by fork() but can’t understand in case of vfork() how pid have two values returned by vfork()?
There aren’t 2 copies. When you cal
vforkthe parent freezes while the child does its thing (until it calls_exit(2)orexecve(2)). So at any single moment, there’s only a singlepidvariable.As a side note, what you are doing is unsafe. The standard spells it clearly:
As a second side note,
vforkhas been removed fromSUSv4– there’s really no point in using it.