gpt4 book ai didi

c - 从父进程到子进程并返回的管道

转载 作者:行者123 更新时间:2023-11-30 16:39:51 26 4
gpt4 key购买 nike

我发现了很多与此类似的问题(例如 https://www.quora.com/How-can-I-write-a-code-for-PIPE-in-C-shell-script-python ),这些问题适用于这些问题描述的情况,但由于某种原因不适用于我的问题。到目前为止,我找到的答案涉及从一个 child 到另一个 child (上述括号内的链接)或从 child 到 parent / parent 到 child 的管道输出。我想做的是让父级能够写入子级的 STDIN 并从其 STDOUT 中读取。或者,在更一般的情况下,给定一定数量的子级,让父级写入第一个子级的 STDIN,这会将其输出通过管道传输到第二个子级,第二个子级将其输出通过管道传输到第三个,依此类推,直到最后一个子级将其输出传送回父级。也就是说,我希望能够做类似 prog0 | 的事情。程序1 |程序 2 | ... 来自 C/C++ 代码。我当前的一半尝试(一半是因为我只是尝试从 echo 的 STDOUT 中读取,然后再使用 cat - 等简单的东西尝试完整的输入/输出)看起来像这样(为简洁起见,省略了一些错误检查):

void test() {
int pipe_fds[2];
pid_t cpid, wpid;
int status;
char buf[16] = {0};

status = pipe(pipe_fds);
cpid = fork();
if (cpid == 0) {
dup2(pipe_fds[1], STDOUT_FILENO);
close(pipe_fds[0]);
execlp("echo", "Hello world!", NULL);
printf("Child returned abnormally: %d\n", errno);
_exit(3);
}

close(pipe_fds[1]);
wpid = waitpid(cpid, &status, 0);
printf("Waited on pid %d, which exited with %d\n", wpid, WEXITSTATUS(status));
read(pipe_fds[0], buf, 16);
printf("Child said: %s\n", buf);
close(pipe_fds[0]);

exit(0);
}

它运行,但父级没有从子级获得可见的输出。我将如何解决这个问题,更重要的是,我将如何像我之前提到的那样通过管道传输到一系列流程?

最佳答案

在这种情况下,问题在于您对 execlp 的调用。尝试一下

execlp("echo", "echo", "Hello world!", NULL); 

关于c - 从父进程到子进程并返回的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46914047/

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