my teacher said that if the writing end of a pipe is closed, the child process can no longer read from the read end of the pipe and a read would generate a BROKEN _PIPE error. However, I can't get this code to generate any error while reading on the closed tube :
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
int main(void) {
int pipefd[2];
char c;
pipe(pipefd);
if (fork() == 0) {
close(pipefd[1]);
sleep(5);
// The parent has already closed pipefd[1]
while (read(pipefd[0], &c, 1)) {
printf("%c", c);
}
close(pipefd[0]);
return 0;
}
close(pipefd[0]);
char str[] = "foo";
write(pipefd[1], str, 4);
close(pipefd[1]);
return 0;
}
The output on stdout after 5 seconds is foo. So what I understand is that closing the write end just add EOF after the characters already there and DOES NOT send EOF on any forthcoming read (so the child can read all the characters already sent). Am I right ?