When I run the following code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = vfork();
printf("hello world\n");
}
Output:
hello world
hello world
hello world
Segmentation fault
I know that unless exec() or _exit() is called then vfork() can behave in strange manner if we try to modify any variable but can someone please explain what exactly is happening?? why hello world is getting printed 3 times? Is it because printf() is getting buffered? and finally why a seg fault is occuring just when parent is trying to return?
(From POSIX.1) The vfork() function has the same effect as fork(2), 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(2) or one of the exec(3) family of functions.
Seems like you violate all the conditions for using vfork. So then it doesn't work.