Write an EOF to a pipe

一个人想着一个人 提交于 2019-12-20 05:21:54

问题


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


回答1:


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

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


来源:https://stackoverflow.com/questions/13521393/write-an-eof-to-a-pipe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!