What happens if the child process does not close the pipe from writing while reading?

Given the following code:

int main(int argc, char *argv[])
{
    int pipefd[2];
    pid_t cpid;
    char buf;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s \n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (cpid == 0) {    /* Child reads from pipe */
        close(pipefd[1]);          /* Close unused write end */

        while (read(pipefd[0], &buf, 1) > 0)
            write(STDOUT_FILENO, &buf, 1);

        write(STDOUT_FILENO, "\n", 1);
        close(pipefd[0]);
        _exit(EXIT_SUCCESS);

    } else {            /* Parent writes argv[1] to pipe */
        close(pipefd[0]);          /* Close unused read end */
        write(pipefd[1], argv[1], strlen(argv[1]));
        close(pipefd[1]);          /* Reader will see EOF */
        wait(NULL);                /* Wait for child */
        exit(EXIT_SUCCESS);
    }
return 0;

}

Whenever a child process wants to read from a pipe, it must first close the pipe from writing. When I delete this line close(pipefd[1]);from the child process if, I basically say that โ€œokay, the child can read from the pipe, but I allow parents to write to the pipe at the same timeโ€?

If so, what happens when the pipe is open for reading and writing? No mutual exclusion?

+5
source share
4 answers

Whenever a child process wants to read from a pipe, it must first close the pipe from writing.

- - , . . , , - , , , EOF. , , ( ), , , .

, (pipefd [1]); IF, , ", , "?

; , , . .

, , - ?

. ; , . ; , .

, , , , . . N , M (, , , N M), . , .

+13

fork() , .

. , . , , , - , " " "EOF", - . .

, .

, / ; , , .

+3

, : . .

1 , .

, fork, , , 2.

" close (pipefd [1])" โ†’ , , while , 0 (.. EOF). , , - 1 ( 2), , .

, "close (pipefd [0]); , , .

, ( ), , ( , ).

, , / . , / .

As if instead of a reading cycle in a child you used only one line below, where you get all the data at a time, and donโ€™t care to check EOF, your program will work even if you do not write "close (pipefd [1]); in a child.

read(pipefd[0], buf, sizeof(buf));//buf is a character array sufficiently large  
+1
source

man page for pipe () for SunOS: - Read the calls to an empty pipe (without buffered data) with only one end (all file descriptor entries are closed) returns EOF (end of file).

 A SIGPIPE signal is generated if a write on a pipe with only
 one end is attempted.
+1
source

All Articles