4

我制作了一个程序,可以创建 5 个管道并在一个循环中分叉 5 个进程。当每个子进程被另一个程序重叠时,我已经设法将数据从父进程发送到每个子进程。每个循环按以下方式完成

父.c):

// Child process - reads from pipe
if (childpid == 0) {
    dup2(fd[0], 0); // replace stdin with pipe input
    execv("program", arguments);

} else { // Parent process - writes to pipe
    write(fd[1], buffer, strlen(buffer)+1);
}

因此,现在我可以通过从子程序使用 execv(...) 执行的程序中的 STDIN_FILENO 读取从父级发送到管道的数据。

像这样(program.c):

char *buffer = (char *)malloc(50);
read(STDIN_FILENO, buffer, 50);

但是,我的问题是,如何将数据发送回父级?我正在考虑通过再次使用 dup2 将标准输出替换为管道输出,但我无法让它工作。我意识到这至少必须在使用 execv(...) 之前完成。


我不确定这个解释是否足够,所以我可以用文字制作一个小图像:)

现在是这样的:

  • 父级 -> 管道
  • 管道 -> 子进程 1
  • 管道 -> 子进程 2
  • 管道 -> ...
  • 管道 -> 子进程 5

我希望它是这样的。

  • 父级 -> 管道
  • 管道 -> 子进程 1
  • 管道 -> 子进程 2
  • 管道 -> ...
  • 管道 -> 子进程 5
  • 子进程 1 -> 父进程
  • 子进程 2 -> 父进程
  • ...
  • 子进程 5 -> 父进程

感谢您的帮助!

4

4 回答 4

4

Pipes are unidirectional, not bidirectional, so a generic solution is to create five more pipes (gak!) for the return data. The parent then needs to use select() system call to know which of the return pipes have data ready for reading.

Oh, and I would have written

    dup2(fd[0], 0); // replace stdin with pipe input
should be
    dup2(fd[0], 0); // replace stdin with output from pipe
and vice versa.

Like the other replies say, there are other communication methods that may be more appropriate, depending on what you are trying to achieve.

于 2010-01-31T15:12:10.357 回答
2

在此处查看此unix 编程常见问题解答,查看问题1.5,也许使用内存映射来允许父/子进程从两端读取/写入...这里有一个很好的了解 IPC 的指南

于 2010-01-31T15:01:41.323 回答
0

我在网上看了一会儿。似乎您只能使用管道以一种方式进行通信。这是有道理的——从标准输入输入并输出到标准输出。如果您想在父进程和子进程之间进行双向通信,请使用套接字。还有其他方法可以实现两路IPC。我建议您了解更多有关进程间通信的信息。

一切顺利。

于 2010-01-31T15:01:17.737 回答
0

如果您想继续使用管道,则制作一组 FD 用于 child->parent 通信,一组用于 parent->child 通信。所以你有 int toParent[2], toChild[2],而不是 int fd[2]。而不是 dup2(fd[0], 0),你有 dup2(toChild[0], 0); dup2(toParent[1], 1)。

并且不要只是重复,而是关闭您不使用的 FD。

于 2012-05-27T21:44:17.043 回答