2014-09-03 35 views
0

我的程序必须创建n个孩子。当接收到信号时,创建一个孩子。然后第一个孩子等待其他n-1个孩子。第二个等待其他n-2个孩子,等到最后一个孩子跑完并立即结束。 我写这段代码,但它不工作,我得到侄子。C:等兄弟进程终止

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <signal.h> 
#include <sys/wait.h> 
void func(int sign) 
{ 
    printf("received signal. I create a child\n"); 
} 

int main(int argc, char*argv[]) 
{ 
    if(argc!=3) 
    { 
     printf("error\n"); 
     return 0; 
    } 
    int i,pid,status; 
    int n=atoi(argv[1]); 
    unsigned int m=(unsigned int)atoi(argv[2]); 
    signal(SIGALRM,func); 
    printf("i'm father: pid %d\n",getpid()); 
    for(i=0; i<n; i++) 
    { 
     alarm(m); 
     pause(); 
     switch(pid=fork()) 
     { 
     case -1: 
      printf("error\n"); 
      break; 
     case 0: 
      printf("i'm the hild numer %d, my pid is %d\n",i,getpid()); 
      if(i!=n-1) 
      { 
       wait(NULL); 
       break; 
      } 
      else 
      { 
       printf("%d i have fnished\n",getpid()); 
       exit(0); 
      } 
      break; 
     default: 
      wait(NULL); 
      break; 
     } 
    } 
    printf("finish\n"); 
    return 0; 
} 
+0

正确的说法是把它称为一个'孩子process' – 2014-09-03 19:04:33

+0

你会需要一些方法来所有的子ID传递给所有的孩子们。否则,第二个孩子将无法等待所有尚未创建的孩子...... – twalberg 2014-09-03 19:10:24

+0

父进程正在启动所有子进程。 wait()函数仅等待* current *进程的子进程。由最后一个孩子创建的代码将终止,(其他孩子都不终止)导致父亲终止(所有其他孩子仍然持有'等待(空)')I.E.所有的孩子都需要一些逻辑来使他们终止。一种方法是父亲初始化一个常用变量,让孩子继续执行,然后在所有孩子生成后重置变量,以便孩子终止。 – user3629249 2014-09-04 20:20:26

回答

1

您的代码结构化的方式是创建2^N进程。

您需要在修改代码:

default: 
    wait(NULL); 
    break; 

的东西,之后没有任何叉更多的孩子。一种方法是使用goto声明。这是一个更新版本。

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <signal.h> 
#include <sys/wait.h> 

void func(int sign) 
{ 
    printf("received signal. I create a child\n"); 
} 

int main(int argc, char*argv[]) 
{ 
    if(argc!=3) 
    { 
     printf("error\n"); 
     return 0; 
    } 
    int i,pid,status; 
    int n=atoi(argv[1]); 
    unsigned int m=(unsigned int)atoi(argv[2]); 
    signal(SIGALRM,func); 
    printf("i'm father: pid %d\n",getpid()); 
    for(i=0; i<n; i++) 
    { 
     alarm(m); 
     pause(); 
     switch(pid=fork()) 
     { 
     case -1: 
      printf("error\n"); 
      break; 

     case 0: 
      printf("i'm the child numer %d, my pid is %d\n",i,getpid()); 
      if(i!=n-1) 
      { 
       wait(NULL); 
       break; 
      } 
      else 
      { 
       printf("%d i have fnished\n",getpid()); 
       exit(0); 
      } 
      break; 

     default: 
      wait(NULL); 
      goto done; 
     } 
    } 

done: 
    printf("%d i have fnished\n",getpid()); 
    return 0; 
}