首页 > 解决方案 > 在 fork() 之后使用 printf 并且父进程处于 wait() 时的意外行为

问题描述

我有以下两组输出不同的代码。[输出到终端]

代码 1:

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

int main ()
{ 
    printf("before the fork\n");
    fflush(stdout);
    int pid=fork();
    printf("after the fork\n");

    if (pid == 0)  
    {
        sleep(1);
        printf("I'm child");
    }
    else   
    {
        wait();
        printf ("I'm parent");
    }
    exit(0);
}

输出 1:

before the fork
after the fork
after the fork
I'm child

现在只有 fork 之后的 printf 被注释了,我们看到父进程的 wait() 之后的 printf 可以正常工作。

代码 2:

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

int main ()
{ 
    printf("before the fork\n");
    fflush(stdout);
    int pid=fork();
    // printf("after the fork\n");

    if (pid == 0)  
    {
        sleep(1);
        printf("I'm child");
    }
    else   
    {
        wait();
        printf ("I'm parent");
    }
    exit(0);
}

输出 2:

before the fork
I'm childI'm parent

我很困惑 fork() 之后的 printf 如何弄乱输出。

请注意以下输出

代码 3:

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

int main ()
{ 
    printf("before the fork\n");
    fflush(stdout);
    int pid=fork();
    printf("after the fork\n");

    if (pid == 0)  
    {
        sleep(1);
        printf("I'm child");
    }
    else   
    {
        //wait();
        printf ("I'm parent");
    }
    exit(0);
}

输出 3:

before the fork
after the fork
I'm parentafter the fork
I'm child

知道为什么会出现这种差异吗?

标签: cforkwait

解决方案


这不是因为 printf("after the fork\n");你得到不同的输出。

原因是当调用 fork() 系统调用时,您会创建一个child process. 并且两者都parent process同时child process运行。所以我们不知道哪个会优先(可能是父母或孩子)。

我在在线编译器中的输出。

在 code2 中,子进程获得了首选项,因此它首先执行,然后是父进程。

同样在代码 3 中,调用了 wait() 系统调用,因此如果父进程获得首选项,它会一直执行到wait(). 之后子进程被执行并且子进程终止后,父进程从它离开的地方继续。

参考这个以获得更多理解


推荐阅读