0

次のコード:

B() { 
   pid_t pid; 
   if ((pid=fork())!= 0) 
       waitpid(pid,NULL,0); 
   printf("2 "); 
   if (fork() == 0) 
      { printf("3 "); exit(0); } 
   printf("5 "); 
   exit(0); 
}

出力の1つを持つことができます:そして、どれが正しい出力かわかりません。

232553
235325
232355
235253
252533

これらの 2 行は、pid が親である場合、何を待つかを意味します。

if ((pid=fork())!= 0) 
           waitpid(pid,NULL,0); 

子プロセス (fork = 0) の場合は、3 を出力します。正しいですか?

 if (fork() == 0) 
              { printf("3 "); exit(0); }
4

2 に答える 2

5
B() { 
   pid_t pid; 

   /* On success, fork() returns 0 to the child. It returns the child's process 
    * ID to the parent. So this block of code, executes a fork(), and has the
    * parent wait for the child.
    * Amusing sidenote: if the fork() fails, the parent will wait for *any* 
    * child process, since the return will be -1.
    */
   if ((pid=fork())!= 0) 
       waitpid(pid,NULL,0); 

   /* Both the parent and the child will print 2. The parent, will, of course,
    * only print 2 after the child exits, because of the waitpid above.
    */
   printf("2 "); 

   /* Now we fork again. Both the parent and the child from the previous fork will
    * fork again, although the parent will do it *after* the child exit. The resulting 
    * child process will print a single 3 and then exit.
    */
   if (fork() == 0) 
      { printf("3 "); exit(0); } 

   /* Now both the parent and the child print a 5 and exit */
   printf("5 "); 
   exit(0); 
}

David Schwartz が言ったように、このプログラムの出力は数字 2、3、および 5 のいくつかの置換で構成されます。出力はプロセスが実行される順序に依存するため、正しい出力はありません。これは任意です。

于 2012-12-09T22:45:24.907 に答える
3

このwaitpid関数は、子プロセスが終了するのを待ちます。あなたが言った他のすべては正しいです。このようなプログラムには、プロセスが実行される順序に依存するため、正しい出力はありません。これは任意です。

   if ((pid=fork())!= 0) 
       waitpid(pid,NULL,0); 

さて、親は子が終了するのを待ちます。

   printf("2 "); 

子はすぐに 2 を出力します。親は、子が終了した後しばらくして 2 を出力します。

   if (fork() == 0) 
      { printf("3 "); exit(0); } 

親と子の両方が分岐します。両方の子が 3 を出力して終了します。

   printf("5 "); 

親と元の子の両方が 5 を出力します。

   exit(0);

親と元の子の両方が出力バッファをフラッシュして終了します。

于 2012-12-09T22:43:36.583 に答える