C 我想知道如何终止进程
我使用fork创建子对象,并尝试每3秒杀死生成的子对象。我还试图用“抚养或杀害”来杀死我的父母。 我不知道如何杀死父处理器。 当我运行我的代码时,除了killparent之外,与我的期望不同的是,有太多的childkill出现了 这就是代码:C 我想知道如何终止进程,c,linux,fork,C,Linux,Fork,我使用fork创建子对象,并尝试每3秒杀死生成的子对象。我还试图用“抚养或杀害”来杀死我的父母。 我不知道如何杀死父处理器。 当我运行我的代码时,除了killparent之外,与我的期望不同的是,有太多的childkill出现了 这就是代码: #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <signal.
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int main()
{
int ch[3];
int i;
for (i = 0; i < 3; i++) {
ch[i] = fork();
if (ch[i] == 0){
printf("child[%d]=%d\n",i,getpid());
exit(0); }
}
for(i = 0; i<3; i++) {
sleep(3);
kill(ch[i],SIGKILL);
printf("Killch[%d]=%d\n",i,ch[i]);
}
/* KILL or raise() parent kill */
}
#包括
#包括
#包括
#包括
#包括
int main()
{
int-ch[3];
int i;
对于(i=0;i<3;i++){
ch[i]=fork();
if(ch[i]==0){
printf(“子[%d]=%d\n”,i,getpid());
退出(0);}
}
对于(i=0;isleep()
不是收集子状态的正确解决方案,请在父级中使用wait()或waitpid()
父母睡觉时
for(i = 0; i<3; i++) {
sleep(3);
kill(ch[i],SIGKILL);
printf("Killch[%d]=%d\n",i,ch[i]);
}
我希望它能帮助你。调用退出(0)
,子进程不会自行消亡吗?你为什么要这样做?这很奇怪,可能有更好的方法来实现你的真正目标。发布的代码无法编译!它缺少以下语句:\include
用于fork()
和getpid())为了便于阅读和理解:1)遵循公理:每条语句只有一条语句(至多)一个变量声明每个语句。考虑关闭括号'}是一个单独的语句,从函数中有3个返回条件:<代码> FURK()<代码>。当调用fork()
失败时,发布的代码不会处理该条件,因此返回-1
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;
}