为什么 vfork() 给出分段错误

why does vfork() giving segmentation fault

当我运行下面的代码

#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

我知道除非调用 exec() 或 _exit(),否则如果我们尝试修改任何变量,vfork() 可能会以奇怪的方式运行,但有人可以解释一下到底发生了什么吗?为什么 hello world 打印了 3 次?是因为 printf() 正在缓冲吗?最后,为什么当父级试图 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.

您似乎违反了所有 使用 vfork 的条件。那么就不行了。

我写的这段代码是一场灾难,将以未定义的方式运行,但对这种行为的合理解释可能是:-

由于地址 space 是共享的,并且当 child 不是 _exit()exec() 时 returning,因此刷新 I/O 缓冲区将被执行(这会导致一个额外的 hello world 语句)并且在清理过程中,当 printf() 的内存被释放时,它可能会将函数调用放在堆栈帧上,而 parent仍然卡住了。 returning 后,parent 可能在堆栈上没有任何 return 地址到 return 给任何人,这会导致分段错误。