2012-01-04 76 views
-1

我需要创建5个进程(不是线程)并使用信号同步它们。同步算法将会像“循环”一样。问题是如何创建5个进程?我可以这样做:我如何创建多个进程

pID = fork(); 

if(pID < 0) { 
    fprintf(stderr, "Fork Failed"); 
    exit(-1); 
} 
else if(pID == 0) { 
    pID = fork(); 

    if(pID < 0) { 
    fprintf(stderr, "Fork Failed"); 
    exit(-1); 
    } 
    else if (pID == 0) { 
     pID = fork(); 

     if (pID < 0) { 
      fprintf(stderr, "Fork Failed"); 
      exit(-1); 
     } else if (pID == 0) { 
      pID = fork(); 

      if (pID < 0) { 
       fprintf(stderr, "Fork Failed"); 
       exit(-1); 
      } else if (pID == 0) {      
       /* Process 5 */ 
       printf("process5 is running... id: %d\n", pID);      
      } else { 
       /* Process 4 */ 
       printf("process4 is running... id: %d\n", pID); 
      } 
     } else { 
      /* Process 3 */ 
      printf("process3 is running... id: %d\n", pID); 
     } 
    } 
    else { 
     /* Process 2 */ 
     printf("process2 is running... id: %d\n",pID); 
    } 
} 
else { 
    /* Process 1 */ 
    printf("process1 is running... id: %d\n",pID); 

    return (EXIT_SUCCESS); 
} 
+2

是的,你可以... – Saphrosit 2012-01-04 22:26:19

回答

4

是的,但循环会更容易让其他人阅读和理解。

int 
call_in_child(void (*function)(void)) 
{ 
    int pid = fork(); 
    if (pid < 0) { 
     perror("fork"); 
     return 0; 
    } 
    if (pid == 0) { 
     (*function)(); 
     exit(0); 
    } 
    return 1; 
} 

然后其他

for (i = 0; i < 4; i++) { 
    if (! call_in_child(some_function)) { 
     ... print error message and die... 
    } 
} 
some_function(); 

的地方,并把你的程序的胆量在some_function。

+0

我会考虑从call_in_child返回孩子pid。 – 2012-01-04 22:45:27