您好我正在尝试在c中编写一些代码,将一个作业分成3个进程,每个进程在答案范围的三分之一中寻找答案(即处理1到10之间的查找,进程b看起来在10之间)和20,过程c看起来在20和30之间)。我正在使用一个简单的for循环,然后在子进程上分叉运行代码。我想,在找到正确答案后,终止所有其他子进程(永远找不到正确答案,因此它们的运行是多余的)。使用sigkill我可以杀死孩子和父母,但可以杀死兄弟姐妹。如何最好地完成这项工作?
for (int i = 0; i < 3; i ++){
int pid = fork();
if (pid == 0){ //this is the child process just forked
char* answer = myFunction(domain[i]);
if (answer != NULL){
printf("answer: %s\n");
//now terminate all other child processes, seeing as their answer was not in their domain
}
break;
}else{
//do nothing as this is the parent process
}
}
}
//handle results