如何解决SIGALRM 在指定时间后未终止程序
我写了一段 C 代码,目的是将 N 作为输入,然后创建 N 个进程并创建一些自己的子进程。每个进程将信号从第 i+1 个进程发送到第 i+12 个进程(是否存在无关紧要)SIGUSR1 信号。如果进程没有收到任何进程的任何信号,则退出该进程。这个想法是在 10 秒后使用 SIGALRM 关闭所有进程,但程序不会终止。如果通过命令行将 N 作为输入,程序可以运行,但如果通过 scanf 获取,它会以某种方式中断。 TIA
static int signal_receive = 0;
void sighandler(int signum){ //////////signal handler for SIGUSR1 signal
signal_receive++;
}
int main(void){
int n;
printf("enter N - ");
scanf("%d",&n);
int id1 = 1,id2 = 1; //////// ids for tracking the process
for(int i = 0; i<n; ++i){
if(id1>0 && id2>0){ /////// only the grandparent can enter
id1 = fork();
int z = getpid()%13;
for(int j = 0; j<z; ++j){
if(id2>0 && id1==0) //////// only the parent can enter
id2 = fork();
}
}
}
alarm(10); ///////// alarm for 10 seconds after which process stops sending SIGUSR1 and exits
while(1){ /////// SIGUSR1 signal
sleep(2);
for(int i = 1; i<13; ++i)
kill(getpid()+i,SIGUSR1);
if(signal_receive==0){
printf("signal exited %d\n",getpid());
exit(0);
}
}
for(int i = 0; i<n*13; ++i)
wait(NULL);
}
解决方法
getpid()+i
你怎么知道第 i 个孩子有那个 pid?这是一个错误的假设。您必须将 pid 存储在表中并使用它来终止相应的进程。类似的东西:
pid_t pids[...];
int n;
...
id = fork();
if (id!=0) pids[n++] = id; // store the new pid in the array
...
...
for (int i=0; i<n; i++)
kill(pids[i],SIGUSR1); // get pids from array and kill them
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。