【发布时间】:2016-03-31 16:22:05
【问题描述】:
所以我有父进程和 5 个子进程。我希望父母与孩子 1、孩子 1 与孩子 2、...、孩子 5 与父母交流。
我能够与除最后一个连接之外的所有子进程进行通信 - 从子进程 5 到父进程。
这是我的代码
int main(void){
pid_t child[CHILDS+1];
int aux = 0, id, i, num, pipes[CHILDS][2];
for(i = 0; i < CHILDS +1; i++){
if((pipe(pipes[i])) == -1){
perror("Pipe failed");
return 1;
}
}
id = babyMaker(child);
srand((unsigned) getpid());
num = rand() % 50 + 1;
if(id == 0){
printf("Parent number: %d\n", num);
close(pipes[i][0]);
close(pipes[CHILDS][1]);
for(i = 0; i < CHILDS; i++){
if(i != id){
close(pipes[i][0]);
close(pipes[i][1]);
}
}
write((pipes[0][1]), &num, sizeof(int));
close(pipes[0][1]);
read(pipes[CHILDS][0], &aux, sizeof(int));
while(wait(NULL) > 0);
close(pipes[CHILDS][0]);
if(aux > num){
num = aux;
}
printf("Greatest number: %d\n", num);
}else{
close(pipes[id-1][1]);
close(pipes[id][0]);
for(i = 0; i < CHILDS; i++){
if(i != id && i != id-1){
close(pipes[i][0]);
close(pipes[i][1]);
}
}
printf("Child %d with number: %d\n",id, num);
read((pipes[id-1][0]), &aux, sizeof(int));
close(pipes[id-1][0]);
if(num < aux){
num = aux;
}
write((pipes[id][1]), &num, sizeof(int));
close(pipes[id][1]);
printf("\nChild %d received the number: %d\n", id, aux);
exit(id);
}
return 0;
}
babyMaker 是我使用 fork() 的地方,它为父级返回 0,为子级返回 1 到 5。
CHILDS 只是标题上定义的变量。
我想检查孩子的号码是否大于收到的号码,如果是,请发送。如果不发送该进程的原始编号。父级打印的数量最多。
我一直在试图弄清楚,但找不到我缺少的东西。如果您需要更多信息,请告诉我。
编辑 1:由于运行代码可能与这里的 babyMaker 和头文件有关。
婴儿制造商
int babyMaker(pid_t *child){
int i;
for(i = 0; i < CHILDS; i++){
if((child[i] = fork()) == 0){
return i+1;
}
}
return 0;
}
头文件
#ifndef HEAD_H
#define HEAD_H
#include <stdio.h>
#include <stdlib.h>
#define CHILDS 5
#endif
在主目录上添加#include“head.h”,一切正常
【问题讨论】:
-
您尝试使用程序解决的问题与Forking and Piping Processes in C 中的问题基本相同。当然,您当前的代码是不同的。
-
在
if(id == 0){ printf("Parent number: %d\n", num); close(pipes[i][0]);中,i的值为CHILDS+1,因此您正在访问超出pipes数组的范围,而close()并未关闭您的意图关闭。我怀疑i应该是0。
标签: c pipe fork parent-child