我正在尝试找出如何将一个进程的输出发送到子进程中。我经历了学习文件描述符和管道的旅程。我想我已经快到了,但缺少一个关键组件。
这是我到目前为止所拥有的:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int fd[2];
pid_t sort_pid;
/* Create the pipe */
if(pipe(fd) == -1) {
fprintf(stderr, "Pipe failed\n");
exit(EXIT_FAILURE);
}
/* create child process that will sort */
sort_pid = fork();
if(sort_pid < 0) { // failed to fork
fprintf(stderr, "Child Fork failed\n");
exit(EXIT_FAILURE);
}
else if(sort_pid == 0) { // child process
close(0); // close stdin
dup2(fd[0], 0); // make stdin same as fd[0]
close(fd[1]); // don't need this end of the pipe
execlp("D:/Cygwin/bin/sort", "sort", NULL);
}
else { // parent process
close(1); // close stdout
dup2(fd[1], 1); // make stdout same as fd[1]
close(fd[0]); // don't need this end of the pipe
printf("Hello\n");
printf("Bye\n");
printf("Hi\n");
printf("G'day\n");
printf("It Works!\n");
wait(NULL);
}
return EXIT_SUCCESS;
}
这不起作用,因为它似乎进入了无限循环之类的。我尝试了 wait() 的组合,但这也没有帮助。
我这样做是为了学习如何将这个想法应用到我的实际程序中。在我的实际程序中,我读取文件,逐行解析它们并将处理后的数据保存到结构的静态数组中。我希望能够根据这些结果生成输出,并使用 fork() 和 execv() 系统调用对输出进行排序。
这最终是为了大学里的一个项目。
这些是我对目前所处阶段进行剖析的类似示例:
- pipe() and fork() in c
- How to call UNIX sort command on data in pipe
- Using dup,pipe,fifo to communicate with the child process
此外,我阅读了相关系统调用的手册页以尝试理解它们。我承认我对管道和使用它们的了解基本上还是一无所知,因为这是我第一次尝试使用它们。
感谢任何帮助,甚至我可以自己研究更多的信息来源。我似乎已经用尽了谷歌搜索给我的大部分有用的东西。
最佳答案
sort
将读取直到遇到文件结尾。因此,如果您希望管道完成,则必须关闭管道的写入端。由于 dup2
,您拥有 open file description 的两个副本,所以你需要
close(fd[1]);
在调用dup2
之后随时close(1);
写入(新的)stdout
后
确保在第二个之前fflush(stdout)
,以确保所有数据实际上已进入管道。
(这是一个简单的死锁示例:sort
正在等待管道关闭,这会在父级退出时发生。但是父级在完成对管道的等待之前不会退出 child 退出...)
关于c - 将 stdout 提供给子进程,该子进程将执行 execv() 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229935/