Search code examples
cpipeeoffgets

Write an EOF to a pipe


I have a parent and a child prozess and want to write an EOF from the parent to the child via a pipe... how does this work?

here is my attampt:

---parent code---

if(dup2(parent_pipe[1], STDOUT_FILENO) == -1) { /*stdout gets closed and parent_pipe is duplicated with id of stdout*/
        error("Can't duplicate the write-end of the pipe to stdout!");
}
if(close(parent_pipe[0]) == -1) {
    error("Can't close read-end of the pipe!");
}

char blub[] = "EOF";
if(write(parent_pipe[1], blub, strlen(blub)) == -1) {
error("Failed to write the array");
}

---child code---

if(dup2(parent_pipe[0], STDIN_FILENO) == -1) { /*stdin gets closed and parent_pipe is duplicated with id of stin*/
    error("Can't duplicate the read-end of the pipe to stdin!");
}
/* close the write-end of the pipe */
if(close(parent_pipe[1]) == -1) {
    error("Can't close write-end of the pipe");
}

while(fgets(readbuffer, ROWLENGTH, stdin) != NULL) {
    printf("Received string: %s", readbuffer, nbytes);
}

the child waits for the EOF and does not stop, how can i fix this problem? thanks in advance


Solution

  • When you want to stop the communication, you must close the pipe in the parent process:

    dup2(...);
    ...
    write to child
    ...
    close(parent_pipe[1]);