我正在尝试找出如何将一个过程的输出发送到子过程中。我已经学习了有关文件描述符和管道的旅程。我想我快到了,但是缺少关键组成部分。
这是我到目前为止所拥有的:
#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 failedn");
exit(EXIT_FAILURE);
}
/* create child process that will sort */
sort_pid = fork();
if(sort_pid < 0) { // failed to fork
fprintf(stderr, "Child Fork failedn");
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("Hellon");
printf("Byen");
printf("Hin");
printf("G'dayn");
printf("It Works!n");
wait(NULL);
}
return EXIT_SUCCESS;
}
这似乎不起作用,因为它似乎陷入了无尽的循环之类的东西。我尝试了Wait()的组合,但这也没有帮助。
我正在这样做是为了学习如何在我的实际程序中应用这个想法。在我的实际程序中,我读取文件,按行分析它们,然后将处理的数据保存到静态的结构阵列中。我希望能够根据这些结果生成输出,并使用fork()和execv()syscalls对输出进行排序。
这最终是针对Uni的项目。
这些是我所阐述的类似示例,到目前为止,我要进入舞台:
- pipe()和fork()在c 中
- 如何调用管道中数据的unix排序命令
- 使用dup,pipe,fifo与儿童过程进行通信
此外,我阅读了相关Syscalls上的手册页,以尝试理解它们。我会承认我对管道的了解,并且使用它们基本上是什么都没有的,因为这是我每次尝试的第一次尝试。
任何帮助都将受到赞赏,甚至我可以研究自己的更多信息来源。我似乎用尽了Google搜索给我的大多数有用的东西。
sort
将读取直到遇到文件结束。因此,如果您希望完成管道,则必须关闭管道的写入端。由于dup2
,您有两个打开文件描述的副本,因此您需要
-
close(fd[1]);
在致电dup2
之后的任何时间 -
close(1);
完成写入(新)stdout
后
确保在第二个之前确保fflush(stdout)
确保您的所有数据实际上都将其纳入管道。
(这是僵局的一个简单示例:sort
正在等待管道关闭,这将在父母退出时发生。但是直到父母完成等待孩子退出&Hellip;)