Search code examples
cforkpipe

C Pipe: Parent to read from child before child ends


The code below shows how a child process can write to a pipe end and then how the parent process can read from the other end. What I noticed after I experimented with the code is that only after the child process is terminated the parent will be able to read the data.

Is there a way to force the parent process to come to the foreground and read the data immediately after the child called write() ? And is there a way to read the data without terminating the child?

#include <stdio.h> /* For printf */
#include <string.h> /* For strlen */
#include <stdlib.h> /* For exit */

#define READ 0 /* Read end of pipe */
#define WRITE 1 /* Write end of pipe */
char *phrase = "This is a test phrase.";
main(){
    int pid, fd[2], bytes;
    char message[100];

    if (pipe(fd) == -1) { /* Create a pipe */
        perror("pipe"); 
        exit(1); 
    }
    if ((pid = fork()) == -1) { /* Fork a child */
        perror("fork"); 
        exit(1); 
    }
    if (pid == 0) { /* Child, writer */
        close(fd[READ]); /* Close unused end */
        write(fd[WRITE], phrase, strlen(phrase)+1);
        close(fd[WRITE]); /* Close used end */
    } 
    else { /* Parent, reader */
        close(fd[WRITE]); /* Close unused end */
        bytes = read(fd[READ], message, sizeof(message));
        printf("Read %d bytes: %s\n", bytes, message);
        close(fd[READ]);  /* Close used end */
    }
}

Solution

  • You are not correct. Try to add the sleep(120) call just before closing the write end of pipe in the 'child' part and run your application.