Boost 管道的用途是什么,为什么它很重要?

What's the purpose of Boost pipe and why it's important?

如果这个问题过于宽泛,我们深表歉意。我是 C++ 的新手,正在尝试了解不同的流类型以及它们为何重要(或无关紧要)。

我正在通过编写启动子进程并处理输出的简单程序来学习。我正在关注 Boost 进程同步 IO 示例:https://www.boost.org/doc/libs/1_75_0/doc/html/boost_process/tutorial.html#boost_process.tutorial.io.

其中一个例子可以简化为:

#include <boost/process.hpp>

using namespace std;
using namespace boost::process;

int main(int argc, char *argv[]) {
  opstream in;
  ipstream out;

  child c("c++filt", std_out > out, std_in < in);

  in << "_ZN5boost7process8tutorialE" << endl;

  in.pipe().close(); // This will help c++filt quit, so we don't hang at wait() forever

  c.wait();
  return 0;
}

我的问题是:

为什么我们必须使用 boost opstream?我可以改用 istringstream 吗(除此之外它无法编译)?可以用 istringstream 编译吗?

Boost文档说:

Boost.process provides the pipestream (ipstream, opstream, pstream) to wrap around the pipe and provide an implementation of the std::istream, std::ostream and std::iostream interface.

成为 pipe 重要吗,即 pipe 在这里有重要意义吗?

什么是进程,它们如何通信?

程序以各种方式与其环境交互。一组通道是标准输入、输出和错误流。

这些通常通过 shell(cmd.exe、sh、bash 等)绑定到终端或文件。

现在如果程序相互交互,例如:

ls | rev

列出文件并将输出发送到另一个程序(rev,它反转每一行),这是用 管道 实现的。管道是一种操作系统功能,而不是一种提升想法。所有主要操作系统都有它们。

Fun fact: the | operator used in a most shells to indicate this type of output/input redirection between processes is called the PIPE symbol.

什么是管道?

管道基本上是指代“IO 通道”而不是文件的“神奇”文件描述符。管道有两端:一方可以向一端写入,另一方可以从另一端读取。

为什么?

马上想到的两个原因

  • 文件需要磁盘 IO 和同步,速度很慢

    Another fun fact: MSDOS has implemented pipes in terms of temporary files (on disk) for a very long time:

    MS-DOS 2.0 introduced the ability to pipe the output of one program as the input of another. Since MS-DOS was a single-tasking operating system, this was simulated by redirecting the first program’s output to a temporary file and running it to completion, then running the second program with its input redirected from that temporary file. Now all of a sudden, MS-DOS needed a location to create temporary files! For whatever reason, the authors of MS-DOS chose to use the TEMP variable to control where these temporary files were created.

  • 管道开启异步IO。如果进程正在进行双向(全双工)IO,这可能很重要。

好的,我在乎吗?

是的,不,也许。

你大多不会。 ipstream/opstream 类 与 std::istream/std::ostream 100% 兼容,所以如果你有一个需要它们的函数:

void simulate_input(std::ostream& os)
{
    for (int i = 0; i < 10; ++i) {
        os << "_ZN5boost7process8tutorialE" << std::endl;
    }
}

你可以在你的示例中完美使用它:

bp::opstream in;
bp::ipstream out;

bp::child c("c++filt", bp::std_out > out, bp::std_in < in);

simulate_input(in);
in.close();

c.wait();

当你确实需要它时

在全双工情况下,您很容易引发死锁,因为两个程序都在等待来自另一端的输入,因为它们正在同步执行 IO。

您可以在此处找到示例和解决方案:

  • Boost::Process Pipe Streams and Unit Test