2

これは私が解くのに苦労している過去の紙の試験問題です。4 つのマークの場合:

Unix システムで見られる fork() システム コールを使用する次の C フラグメントを考えてみましょう。

while (fork()==0) {
  if (fork()==0) break;
}

このコードを実行することによって生成される親子構造を明確に示す図 (ツリー形式) を描画します。このコードを実際に実行すると、最終的にどのような効果が得られるでしょうか?

子プロセスを継続的に作成していると思いますが、コードのコンテキストでは説明できません。while は毎回 fork を継続的に呼び出しますか、それとも if ステートメントで毎回呼び出されるだけですか?

ありがとう!

4

2 に答える 2

9

while ループは、括弧内の条件が false になるまで実行されます。この場合、次のようになります: からの戻り値fork()が 0 に等しくなくなるまで。

fork()のリターンは次のとおりです。

成功すると、子プロセスの PID が親に返され、0 が子に返されます。失敗すると、親に -1 が返され、子プロセスは作成されず、errno が適切に設定されます。

したがって、フォークが正常に実行されると、2 つのプロセス (親プロセスと新しい子プロセス) が存在します。そのうちの 1 つは 0 (子プロセス) を返し、もう 1 つ (親プロセス) は別の値 (子の PID) を返します。

したがって、これは、各子プロセスが while() ループを実行し続けるため、コードが永久に実行されることを示しています。

親が PID=0 †</sup>、最初の子が PID=1 †</sup> などとします。コードの最初の実行は次のようになります。

while(fork()==0)  // now there are two processes, the child which returns 0 and the
{                 // parent which returns 1 (the new child's pid)

    if(fork() == 0) break;  // this code is now only executed by the child (1) as the 
                            // parent already left the while loop since it's return was
                            // not == 0
                            // once this code executes there are 2 processes running
                            // child(1) will return child(2)'s PID, child(2) will
                            // return 0 and will enter the if and break from the loop 
    // now here it's only the original child(1) running again
}

したがって、次のような結果になります。

0 is the original parent, it makes a child and leaves
1 is the original child, it creates a child(2) and then goes to the while loop again
     where it generates 3 before leaving
2 is the child of 1 where it leaves because of the break in the if
3 now hits the if and generates 4 (which leaves because of the break)
3 now goes back to while and generates 5 then leaves, 
etc
etc
              +--> 4
              |
              | (if)
              |
0 --> 1 -+--> 3 ---> 5
         |
         |(if)
         |
         +--> 2

† - これらは、最新の Linux ディストリビューションでユーザー空間コードを実行しているときに取得する現実的な PID ではありませんが、実際のランダムな文字列よりも読みやすいので、私はそれらを使用しています。

于 2013-04-30T12:45:53.637 に答える