将EOF写入管道

时间:2012-11-22 23:38:02

标签: c pipe eof fgets

我有一个父母和一个孩子,并希望通过管道从父母给孩子写一个EOF ......这是如何工作的?

这是我的嫌疑人:

---父代码---

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");
}

---子代码---

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);
}
孩子等待EOF并且没有停止,我该如何解决这个问题? 提前谢谢

1 个答案:

答案 0 :(得分:4)

如果要停止通信,则必须在父进程中关闭管道:

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