如何通过管道将最后一个 child 的数字发送到 parent?

How to send a number from last child to parent through a pipe?

所以我有 parent 个进程和 5 个 child 个进程。我希望 parent 与 child 1、child 1 与 child 2、...、child 5 与 parent 通信。

我能够与所有 child 通信,除了最后一个连接 - 从 child 5 到 parent 进程。

这是我的代码

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;
}

我使用 fork() 的 babyMaker 为 parent 返回 0,为 child 返回 1 到 5。

CHILDS 只是 header 上定义的变量。

我想检查 child 上的号码是否大于收到的号码,如果是,请发送。如果不发送该进程的原始号码。 parent 打印出最大的数字。

我一直在努力弄清楚,但找不到我遗漏的东西。如果您需要更多信息,请告诉我。

编辑 1:因为它可能与 运行 有关,所以这里的代码是 babyMaker 和 header 文件。

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]);

这是无效的,因为它被定义为管道[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];