Rachit Tayal
Rachit Tayal

Reputation: 1292

why does vfork() giving segmentation fault

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?

Upvotes: 1

Views: 891

Answers (2)

Rachit Tayal
Rachit Tayal

Reputation: 1292

The piece of code I have written is a disaster and will behave in an undefined way but the plausible explanation for such a behavior could be:-

Since the address space is shared and when the child is returning not by _exit() or exec(), therefore flushing of I/O buffers would be performed ( which leads to an extra hello world statement) and during the clean up process when memory to printf() is freed, it may put function calls on the stack frame, while the parent is still stuck. Upon returning the parent might not have any return address on the stack to return to anyone, which results in segmentation fault.

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92321

(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.

Upvotes: 1

Related Questions