Warm tip: This article is reproduced from serverfault.com, please click

How do you read from pipe with both children in C?

发布于 2020-12-03 16:40:14
int main()
{
    int pipefd[2];
    char buf;

    int pid, pid1;
    pid = fork();

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    if(pid == 0){                    // CHILD 1
        close(pipefd[1]);

        while(read(pipefd[0],&buf,1) > 0){                       // THIS DOESNT WORK
            printf("FIRST CHILD WRITES: %s\n",&buf);             // THIS DOESNT WORK
        }                                                        // THIS DOESNT WORK
        close(pipefd[0]);
        _exit(EXIT_SUCCESS);

    }else{
        pid1 = fork();

        if(pid1 == 0){                     // CHILD 2
            close(pipefd[1]);

            // while(read(pipefd[0],&buf,1) > 0){                 // ONLY THIS (WOULD) WORK
            //     printf("SECOND CHILD WRITES: %s\n",&buf);      // ONLY THIS (WOULD) WORK
            // }                                                  // ONLY THIS (WOULD) WORK

            close(pipefd[0]);
            _exit(EXIT_SUCCESS);

        }else{                               // PARENT
            close(pipefd[0]);
            char* s = "Write To Pipe";
            write(pipefd[1],s,strlen(s));
            close(pipefd[1]);

            wait(NULL);            // WAIT FOR CHILD TO TERMINATE
            wait(NULL);            // WAIT FOR CHILD TO TERMINATE
        }
    }

    return 0;
}

Whenever I try to run the program only the 2ND CHILD can read from the pipe, the 1ST CHILD never. So I tried commenting the second child's pipe reading, however the first child still can't read from the pipe to which the parent wrote into.

Why can't the 1ST CHILD read from the pipe?

Thanks for the help!

Questioner
PizzaPeet
Viewed
0
William Pursell 2020-12-04 00:50:26

The order is wrong. Your code is

pid = fork();

if (pipe(pipefd) == -1) {
    perror("pipe");
    exit(EXIT_FAILURE);
}

You need to create the pipe before you fork. You would probably catch this type of error if you check for errors on the close and/or the read.