问题
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()?
回答1:
There aren't 2 copies. When you cal vfork
the parent freezes while the child does its thing (until it calls _exit(2)
or execve(2)
). So at any single moment, there's only a single pid
variable.
As a side note, what you are doing is unsafe. The standard spells it clearly:
The vfork() function shall be equivalent to fork(), except that the behavior is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.
As a second side note, vfork
has been removed from SUSv4
- there's really no point in using it.
来源:https://stackoverflow.com/questions/9347928/return-value-in-vfork-system-call