[英]C: Wait for brothers process termination
我的程序必须创建n个孩子。 收到信号后,将创建一个孩子。 然后第一个孩子等待其他n-1个孩子。 第二个等待其他n-2个孩子,依此类推,直到最后一个孩子跑完并立即完成。 我写了这段代码,但是没有用,我有了侄子。
#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;
}
代码的结构方式是创建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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.