当我运行以下代码时
#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() 正在缓冲吗?最后为什么当父进程试图返回时会发生段错误?
最佳答案
(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 的所有条件。那么它就不起作用了。
关于c - 为什么 vfork() 会出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794290/