4

次のコードを実行すると:

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

int main()
{
    pid_t pid, pid1;
    fflush(stdout);
    pid = fork();
    fflush(stdout); 
    pid1 = fork();
    if(pid==0)
    {
         printf("%d is the first child\n", getpid() );
    }
    else if(pid>0)
    {
         printf("%d is the first parent\n", pid);
        wait();
    }
    if(pid1==0)
    {
         printf("%d is the second child\n", getpid() );
    }
    else if(pid1>0)
    {
         printf("%d is the second child\n", pid1);
        wait();
    }

    return 0;
}

出力が得られます:

2896 is the first parent
2896 is the first child
2898 is the first child
2898 is the second child
2898 is the second child
2896 is the first parent
2897 is the second child
2897 is the second child

出力が理解できません。同じ文字列が複数回出力されるのはなぜですか?

4

3 に答える 3

11

合計 3 つのフォークを実行しています。最初pid = fork()は、元のプロセスで実行され、さらに 1 つのプロセスが発生したため、合計は 2 つになり、両方ともコードの次の行から続きます。

次にpid1 = fork()、これらの両方で実行され、さらに2つの子プロセスが生成されるため、合計は 4 になり、それぞれが再び次の行 (最初の if) に続きます。

次に、3 つのプロセスすべてが 2 つの if-else ステートメントを処理し (fork エラーがないと仮定)、各プロセスが 2 行を出力します。したがって、4 つのプロセスに 2 行を掛けると 8 行になります。あなたが得ているもの。

したがって、プロセスは次のとおりです。

  • オリジナル
  • 第 1 世代の年長の子供、第 1 フォーク ステートメントから
  • 初代年下の子、原作による2ndフォーク発言より
  • 2世子、年上の1世子による2ndフォーク発言より

出力を理解したい場合は、これら 4 つのプロセスすべてについて頭の中でコードをステップ実行してください。現在印刷しているものに加えて、各印刷ステートメントで現在の pid を印刷すると役立つ場合もあります。

于 2013-01-29T13:05:44.527 に答える
0

また、以下のコードで同じ文字列を誤って出力していると思います

else if(pid1>0)
{
    printf("%d is the second child\n", pid1); // This "child" should be "parent"
    wait();
}
于 2016-04-18T11:47:13.977 に答える