c - 为什么 vfork 会产生这个输出?

标签 c linux unix process

<分区>

#include <unistd.h>
#include <stdio.h>

static void f1(void);
static void f2(void);

int main(void)
{
    printf("process id:%d\n", getpid());
    f1();
    f2();
    _exit(0);
}

static void f1(void)
{
    pid_t pid;

    if((pid = vfork()) < 0)
    {
        printf("vfork error\n");
    }
}
static void f2(void)
{
    char buf[1000];
    int i;

    for(i = 0;  i < sizeof(buf); i++)
    {
        buf[i] = 0;
    }

    printf("f2:process id:%d\n", getpid());
}

上述程序的输出是:

process id:9956
f2:process id:9957

Vfork 确保子进程在父进程之前执行,所以我认为当从函数 f1() 返回时,子进程将执行 f2(),然后是 _exit(0);之后,为什么父进程不执行函数f2()

最佳答案

我假设您在问题正文中输入了错误的 fork 而不是 vfork。如果是这种情况,您就是在滥用 vfork。一旦发出 vfork,除了 exec 或退出之外,您不应该对 child 做任何事情。

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

关于c - 为什么 vfork 会产生这个输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21256029/

上一篇:c - 链表,C 程序

下一篇:c - 段错误 (11)

相关文章:

c++ - 如何通过 UNIX 套接字发送 std::vector<std::string> ?

mysql - 为什么 MySQL 的 ENCRYPT 在每次调用时返回不同的结果?

c - 是否可以使用 Sage 来计算数据结果

linux - 确定文件系统是否以只读方式挂载的最佳 POSIX 方法

regex - 移动以编号开头且类型为 pdf 的文件

c - 子线程的栈空间

c# - 从 c 到 c# 的 double 组编码

c - union 嵌套在返回垃圾值的结构中

c - while ((len = getline(line, MAXLINE)) > 0) -- 为什么设置>0?

linux - 找不到意外的运算符(Bash 错误)