#Reading from a pipe in the parent process

5 messages · Page 1 of 1 (latest)

elder tulip
#

I'm trying to get what I wrote in a child process in a pipe from the parent process, but when I read from the pipe I'm not getting anything, and I don't understand why. I googled a lot for similar problems, and I didn't saw any difference.

Here's a Minimal, Reproducible Example:

#include <stdlib.h>
#include <stdio.h>

#include <unistd.h>
#include <sys/wait.h>

#include <string.h>

#define READ  0
#define WRITE 1

int main(int argc, char **argv) {
    pid_t pid = fork();

    int fd[2];

    char buffer[20];

    char message[] = "Hello";

    pipe(fd);
    if(fd[READ] < 0 || fd[WRITE] < 0){
        puts("Pipe creation failed");
        return EXIT_FAILURE;
    }

    if(pid == 0){
        /* Child */
        close(fd[READ]);
        write(fd[WRITE], message, strlen(message));
        close(fd[WRITE]);
    }else{
        /* Parent */
        close(fd[WRITE]);
        wait(NULL);
        read(fd[READ], buffer, 20);
        close(fd[READ]);
        puts(buffer);
    }
    return EXIT_SUCCESS;
}
rugged cypressBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

compact hollow
#

youre calling pipe after fork, why ?

elder tulip
#

Oh thanks, I didn't saw it, maybe I should sleep more, that was dumb, sorry!

#

!solved