[英]How to send a number from last child to parent through a pipe?
所以我有父进程和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”,一切正常
对于此行:
id = babyMaker(child);
id的值为1到5。
这意味着这一行:
close(pipes[id][0]);
可以变成
close(pipes[5][0]);
这是无效的,因为它被定义为pipe [5] [2]。 这是一个错误的错误。
同样,由于相同的原因,这些行也是无效的:
close(pipes[CHILDS][1]);
read(pipes[CHILDS][0], &aux, sizeof(int));
close(pipes[CHILDS][0]);
也许您的意思是这样的:
int aux = 0, id, i, num, pipes[CHILDS][2];
是这样的:
int aux = 0, id, i, num, pipes[CHILDS+1][2];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.