c - 为什么 vfork() 会出现段错误

标签 c process linux-kernel vfork

当我运行以下代码时

#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/

相关文章:

c - 我正在尝试使用 C 编码从 linux 制作 uniq 命令

C - 打开/读取垃圾箱

c++ - 关闭控制台时如何正确处理 SIGBREAK?

C、功能太长不规范

android - android 应用程序中的 process.waitFor() 返回 "1"

c - 跨进程共享库

linux - 从文件系统中查找路由器固件的 linux 内核版本

android - 如何直接发送触摸事件到/dev/input/event?

linux - 从 i.MX51 中的内核升级 u-boot

c++ - 如何将 char 数组中的值与另一个 char 进行比较