我的程序创建了一个子进程,每个子进程数(+5)如果超过100,他向父进程发送信号,父进程应该杀死这个子进程 我做了这个程序,但它不会工作,它一直在计算第一个孩子,这意味着SIGKILL在这里没有任何帮助吗?
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
pid_t pids[10];
int pidval[10];
int l;
void handler1(int mysignal)
{
int i;
for (i=0; i<l; i++) {
if (pidval[i]>100) {
kill(pids[i], SIGKILL);
printf("\n killed ");
}
}
}
int main(int argc, char ** argv)
{
int i, s;
l = atoi(argv[1]);
pid_t pid;
for(i=0; i<l; i++)
{
pid=fork();
if(pid<0)
printf("\n error \n");
if (pid==0) {
pids[i] = getpid();
while(1) {
s+=5;
if(s>100)
{
pidval[i]=s;
printf("\noverflow,%d,%d,%d",s,pids[i],getpid());
kill(getppid(), SIGALRM);
};
}
}
if(pid>0) {
signa(SIGALRM,handler1);
waitpid(-1,NULL,0);
}
}
}
答案 0 :(得分:1)
使用SIGTERM,看看这个article。
答案 1 :(得分:0)
我感谢你的建议
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
void handler1(int mysignal)
{
FILE *pids = NULL;
FILE *pidvals=NULL;
int pid1,pid2,val,sum;
pids=fopen("pids.txt","r");
while(fscanf(pids,"pid = %d\n",&pid1)!=EOF)
{ pidvals=fopen("vals.txt","r");
while((fscanf(pidvals,"pid = %d val = %d\n",&pid2,&val)!=EOF))
{
if(pid1==pid2)
sum+=val;
}
fclose(pidvals);
if(sum>100) kill(pid1,SIGTERM);
}
fclose(pids);
}
int main(int argc, char ** argv)
{ FILE *pids = NULL;
FILE *pidvals=NULL;
int i, s;
int l=atoi(argv[1]);
pid_t pid;
for(i=0;i<l;i++)
{
pid=fork();
if(pid<0) printf("\n error \n");
if (pid==0) {pids=fopen("pids.txt","a");
fprintf(pids,"pid = %d\n",getpid());
fclose(pids);
s=0;
while(1){
s+=5;
pids=fopen("vals.txt","a");
fprintf(pids,"pid = %d val = %d\n",getpid(),s);
fclose(pids);
if(s>100)
{
printf(" \nsend signal\n");
kill(getppid(),SIGALRM);};
}
}
if(pid>0) {
signal(SIGALRM,handler1);waitpid(-1,NULL,0);
}
}
}