sleep()
は、子ステータスを収集するための正しい解決策ではありません。親にを使用してください。
親があなたのコードchild
で睡眠
for(i = 0; i<3; i++) {
sleep(3);
kill(ch[i],SIGKILL);
printf("Killch[%d]=%d\n",i,ch[i]);
}
のときに殺すために親を待っていませんか?子供はexit(0)
声明によってそれ自身によって殺される。
あなたはexit status
を親と親の必要に応じて送信する必要がありますcollect
子供のステータスはを使用していますか?
親が子供を殺しているかどうかを観察したい場合は、子供の遅延を使用して観察してください。
「私は生成された子供を殺そうとしますか?親と仮定して、私のコードは
int a[3];
int temp[3]; //to set flag=1 , when child completes instruction and become zombie
//collect status in wait() in parent, so no need to further process in my_isr
void my_isr(int n) //if child has not completed instruction, i.e not removed by wait() in parent
{ //then remove it using my_isr
printf("in isr..\n");
static int i;
for(;i<3;i++)
if((temp[i]!=1))//if first child "not turned into zombie and removed by parent" then kill it
{
printf("child %d killed \n",i+1);
kill(a[i],SIGKILL);
}
else
{
printf("zombie child %d has been terminated normally \n",i+1);
}
}
int main()
{
if((a[0]=fork()) == 0)
{
int r;
srand(getpid());
r=rand()%10+1;
printf("child %d is going for sleep of %d sec\n",getpid(),r);
sleep(r);
exit(1);
}
else
{
if((a[1]=fork()) == 0)
{
int r;
srand(getpid());
r=rand()%10+1;
printf("child %d is going for sleep of %d sec\n",getpid(),r);
sleep(r);
exit(2);
}
else
{
if((a[3]=fork()) == 0)
{
int r;
srand(getpid());
r=rand()%10+1;
printf("in child %d is going for sleep of %d sec\n",getpid(),r);
sleep(r);
exit(3);
}
else
{
int s;
printf("in parent : %d \n",getpid());
signal(SIGALRM,my_isr);
//setting timer to tell child's that you need to completes within this duration
alarm(5);
while(wait(&s) != -1)//when there is no child left , wait returns -1
{
if(s>>8 == 1)
temp[0]=1; //set the flag when exit status is received
else if(s>>8 == 2)
temp[1]=1; //set the flag when child completed work before
else if(s>>8 ==3)
temp[2]=1; //set the flags when zombies are removed
}
}
}
}
return 0;
}
私はそれがあなたを助けてくれることを願っています。
子プロセスが 'exit(0)'を呼び出すことによって自分自身で死ぬことはありませんか? –
なぜこのことをしたいですか?奇妙で、あなたの真の目標を達成するためのより良い方法があるでしょう。 – zwol
投稿されたコードはコンパイルされません! 'fork()'と 'getpid()と' sleep()関数には '#include'という文がありません。 –
user3629249