user7475082
user7475082

Reputation:

Read from pipe even if the write end is closed

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 ?

Upvotes: 2

Views: 7011

Answers (1)

UniversE
UniversE

Reputation: 2507

As you have found out, your teacher is wrong.

You do not get a broken pipe "error" (which is actually a combination of a signal, SIGPIPE, and an error EPIPE if that is ignored), when you try to read from a broken pipe, but when you attempt to write to a broken pipe.

For Linux systems, you can read more about this here, or you can take a look at the BSD man page pipe(2).

Upvotes: 8

Related Questions