The code below shows how the child process can write to the end of the pipe , 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 as the child process is complete , the parent will be able to read the data.
Is there a way to make the parent process come to the fore and read the data right after the child calls write () ? And is there a way to read data without interrupting a child?
#include <stdio.h> /* For printf */
#include <string.h> /* For strlen */
#include <stdlib.h> /* For exit */
#define READ 0
#define WRITE 1
char *phrase = "This is a test phrase.";
main(){
int pid, fd[2], bytes;
char message[100];
if (pipe(fd) == -1) {
perror("pipe");
exit(1);
}
if ((pid = fork()) == -1) {
perror("fork");
exit(1);
}
if (pid == 0) {
close(fd[READ]);
write(fd[WRITE], phrase, strlen(phrase)+1);
close(fd[WRITE]);
}
else {
close(fd[WRITE]);
bytes = read(fd[READ], message, sizeof(message));
printf("Read %d bytes: %s\n", bytes, message);
close(fd[READ]);
}
}
source
share