管道:错误的文件描述符

时间:2019-03-18 10:35:03

标签: c pipe file-descriptor

我知道以前曾问过这类帖子,但是它们的级别显然比我想的要高,阅读他们的帖子后我仍然听不懂,所以我决定从这里再次发布这个问题。

我正在学习使用管道进行多进程通信,我遇到了称为错误文件描述符的错误,我不明白为什么我的代码中存在此错误。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#define SIZE 50

struct record {
    int freq;
    char word[SIZE];
};

int main(){

int number_process = 3;
int pipes[number_process][2];

struct record r1;
r1.freq = 10;
strcpy(r1.word, "Cat");

struct record r2;
r2.freq = 20;
strcpy(r2.word, "Elephant");

struct record r3;
r3.freq = 30;
strcpy(r3.word, "Dragon");

struct record records_array[3] = {r1, r2, r3}; 

for (int i = 0; i < number_process; i++){

    if (pipe(pipes[i]) == -1){
        perror("pipe");
        exit(1);
    }

    // Create children.
    pid_t fork_result = fork();
    if (fork_result == -1){
        perror("Parent fork");
        exit(1);
    } else if (fork_result == 0){

        if (close(pipes[i][0]) == -1){
            perror("Child closes reading port");
            exit(1);
        }

        // Later children is going to close all reading port from pipe that parent creates.
        for (int child_no = 0; child_no < i; child_no++) {
            if (close(pipes[child_no][0]) == -1) {
                perror("close reading ends of previously forked children");
                exit(1);
            }
        }

        // Now, I am trying to write each strct record member from the above array into the pipe
        // when I run the program, it won't allow me to do so because of bad file descriptor exception.
        for (int j = 0; j < number_process; i++){
            if (write(pipes[i][1], &(records_array[j]), sizeof(struct record)) == -1){
                perror("write from child to pipe");
                exit(1);
            }
        }

        // Finishing writing, close the writing end in pipe.
        if (close(pipes[i][1]) == -1){
            perror("Child closes writing port");
            exit(1);
        }
        // Terminate the process.
        exit(0);

    } else {
        // Parent is closing all the writing ends in pipe.
        if (close(pipes[i][1]) == -1){
            perror("Parent close writing");
            exit(1);
        }

    }

}
    return 0;

}

当我完成编译并运行可执行文件时,它只是告诉我发生了错误的文件描述符。我尝试使用gdb仔细查看可能发生此错误的位置,并且我注意到gdb甚至在调用write()之前都会报告此错误。

我对编写和管道的概念完全迷失了,可以请有人向我解释在此过程中我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您的问题与您正在使用的任何系统调用无关。更平凡。 for (int j = 0; j < number_process; i++)是一个错误。您正在使用i访问文件描述符数组,并错误地对其进行递增。您打算增加j