2016-04-05 7 views
0

は、私は1人の親と4つのチャイルズをしたいし、それらを作成した後、私のようなもの印刷:同じ親に対して4つの子プロセスを作成し、4つの子プロセスが完了するのを待つ方法はありますか?

[PID] (parent) with child processes: [PID1] [PID2] [PID3] [PID4] 

をし、親が終了するそれらのすべてを待ちます。

このコード(How to use Fork() to create only 2 child processes?)をループなどで使用できますか?

私はこれを行うために管理:

 main() 
{ 
    int pid, state, loop1=4, loop2, i=1, j; 
    printf(" Parent before fork()\n"); 
    if ((pid=fork()) !=0) 
    { 
     ParentPID=pid; 
     wait(&state); 
    } 
    else 
    { 
     while(loop1!=0) 
     { 
      execl("child", 0); 
      a[i]=pid; 
      loop1--; 
      i++; 
     } 
    } 
    printf("Parent after fork()\n"); 
    for (j=1; j<i; ++j) 
    { 
     printf ("PARENT_PID:"%d" CHILD_PID[" %d "]= "%d,ParentPID, j, a[i]); 
    } 
    //printf("\tId process child=%d; finished with %d=%x\n",pid,state,state); 
} 

main() 
{ 
    int pid; 
    printf("Child: the execution starts \n"); 
    pid=getpid(); 
    printf("Child: %d execution finished\n", pid); 
    exit(pid); 
} 
+1

あなたがXの子供を望むなら、あなたが呼び出す必要があります[ 'fork'](http://man7.org/linux/man-pages/man2/fork.2.html)親プロセスのX回*。個別に行う場合や、ループ内で問題にならない場合、重要な部分は、親プロセスで行うことです。 –

+0

親プロセスの "in"とはどういう意味ですか?私に例を挙げてください。 – Marko

+0

['fork'](http://man7.org/linux/man-pages/man2/fork.2.html)呼び出しが返すものは何ですか?あなたが親プロセスか子プロセスかをチェックする方法を知っているか(['fork'](http://man7.org/linux/man-pages/man2/fork.2.html)失敗した)? –

答えて

2

ソリューションは次のようになります。詳細は

#include <sys/types.h> 
#include <sys/wait.h> 
#include <stdio.h> 
#include <unistd.h> 

void childFunction(){ 
    printf("Child : %d\n", getpid()); 
    // do stuff 
} 

int main(){ 
    int childLimit = 3; // number of children wanted 
    int childrenPids[childLimit]; // array to store children's PIDs if needed 
    int currentPid, i; 

    for(i=0; i<childLimit; i++){ 
     switch(currentPid = fork()){ 
      case 0: 
       // in the child 
       childFunction(); 
       // exit the child normally and prevent the child 
       // from iterating again 
       return 0; 
      case -1: 
       printf("Error when forking\n"); 
       break; 
      default: 
       // in the father 
       childrenPids[i] = currentPid; // store current child pid 
       break; 
     } 

    } 

    printf("Father : %d childs created\n", i); 

    // do stuff in the father 

    //wait for all child created to die 
    waitpid(-1, NULL, 0); 
} 

man waipidを参照してください。)

+0

"すべての子が死ぬのを待つ" ... ALLを待たずに、子プロセスのいずれかが終了すると 'waitpid()'呼び出しが戻ります。 –

+0

この回答は、OPが出力したいと言った行を出力しません。 – user3629249

+0

@Monstercrunch: ケースの構造では、デフォルト値のcurrentPidだけをキャッチしても構いません。私はすべての正しく作成された子供のためのこの情報が欲しい。私はchildrenPids [i] = currentPidステートメントが0のケースに入るはずだと信じています。 – Marko

関連する問題