c - 如何通过管道将最后一个 child 的号码发送给 parent ?

标签 c pipe fork parent-child

所以我有一个父进程和 5 个子进程。我希望家长与 child 1 沟通, child 1 与 child 2 沟通,..., child 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只是标题上定义的变量。

我想检查 child 的号码是否大于收到的号码,如果是则发送。如果没有发送该进程的原始编号。父级打印最多的数字。

我一直在试图找出答案,但找不到我错过的东西。如果您需要更多信息,请告诉我。

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

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

关于c - 如何通过管道将最后一个 child 的号码发送给 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36338755/

相关文章:

c - 有没有办法使用 CUPS API 来保留打印作业?

c - 读取整个管道 - c

c - 如何正确关闭管道

C++:是否可以通过 fork 进程共享指针?

ant - 在不使用 spawn=true 的情况下在后台运行 Ant 目标

c - 基于堆栈的缓冲区溢出漏洞

c - 内部推广 : Is the following well-defined?

将 arr 的字符一个一个连接到空字符串

Angular 2货币管道格式

multithreading - 可以使用多线程并行运行 100 个 perl 脚本吗?