簡體   English   中英

在 fork() 之后使用 printf 並且父級處於 wait() 狀態時出現意外行為

[英]Unexpected behavior when printf is used after fork() and the parent is on 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

知道為什么會有這種差異嗎?

這不是因為printf("after the fork\\n"); 你得到不同的輸出。

原因是當 fork() 系統調用被調用時,您會創建一個child process 並且parent processchild process都同時運行。 所以我們不知道哪個會獲得優先權(可能是父母或孩子)。

我在在線編譯器中的輸出。

在 code2 中,子進程獲得了首選項,因此它首先執行,然后是父進程。

同樣在代碼 3 中,調用了 wait() 系統調用,因此如果父進程獲得了優先級,它將一直執行到wait()為止。 之后子進程被執行,子進程終止后,父進程從它離開的地方繼續。

參考這個以獲得更多的理解

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM