Return value in vfork () system call

Given the code below:

int main() { int pid; pid=vfork(); if(pid==0) printf("child\n"); else printf("parent\n"); return 0; } 

In the case of vfork (), the address space used by the parent process and the child process will be the same, so there must be one copy of the pid variable. Now I cannot understand how this pid variable can have two values ​​returned by vfork () , i.e. Zero for child and zero for parent?

In the case of fork (), the address space is also copied, and in each child and parent instance there are two copies of the pid variable, so I can understand that in this case two different copies can have different values, fork () is returned, but it cannot understand in the case of vfork () , how does pid have two values ​​returned by vfork () ?

+6
source share
1 answer

There are no two copies. When you cal vfork , the parent freezes while the child does his thing (until he calls _exit(2) or execve(2) ). Therefore, at any moment there is only one pid variable.

As a side note, what you do is unsafe. The standard reads:

The vfork () function should 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 return from functions in which vfork () was called or calls any other function before successfully calling _exit () or one of the exec function families.

As the second side of the note, vfork been removed from SUSv4 - there really is no point in using it.

+6
source

Source: https://habr.com/ru/post/908818/


All Articles