gpt4 book ai didi

c - 将 EOF 写入管道

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:28 24 4
gpt4 key购买 nike

我有一个父进程和一个子进程,我想通过管道将 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");
}

--- child 代码---

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

child 等待 EOF 并没有停止,我该如何解决这个问题?提前致谢

最佳答案

当要停止通信时,必须关闭父进程中的管道:

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

关于c - 将 EOF 写入管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13521393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com