简体   繁体   English

如何在 c++ 中制作 pipe

[英]How to make a pipe in c++

I'm looking at the code for a c++ program which pipes the contents of a file to more.我正在查看 c++ 程序的代码,该程序将文件的内容通过管道传输到更多。 I don't quite understand it, so I was wondering if someone could write pseudocode for a c++ program that pipes something to something else?我不太明白,所以我想知道是否有人可以为 c++ 程序编写伪代码,将某些东西通过管道连接到其他东西? Why is it necessary to use fork?为什么需要使用fork?

create pipe
fork process
if child:
  connect pipe to stdin
  exec more
write to pipe

You need fork() so that you can replace stdin of the child before calling, and so that you don't wait for the process before continuing.您需要fork()以便您可以在调用之前替换孩子的标准输入,这样您就不必等待该过程再继续。

Why is it necessary to use fork?为什么需要使用fork?

When you run a pipeline from the shell, eg.当您从 shell 运行管道时,例如。

$ ls | more

what happens?怎么了? The shell runs two processes (one for ls , one for more ). shell 运行两个进程(一个用于ls ,一个用于more )。 Additionally, the output (STDOUT) of ls is connected to the input (STDIN) of more , by a pipe.此外, ls的 output (STDOUT) 通过 pipe 连接到more的输入 (STDIN)。

Note that ls and more don't need to know anything about pipes, they just write to (and read from) their STDOUT (and STDIN) respectively.请注意, lsmore不需要了解有关管道的任何信息,它们只需分别写入(和读取)它们的 STDOUT(和 STDIN)。 Further, because they're likely to do normal blocking reads and writes, it's essential that they can run concurrently.此外,由于它们可能会进行正常的阻塞读取和写入,因此它们可以同时运行是必不可少的。 Otherwise ls could just fill the pipe buffer and block forever before more gets a chance to consume anything.否则ls可能只会填充 pipe 缓冲区并在more有机会消耗任何东西之前永远阻塞。

... pipes something to something else... ...管道的东西到别的东西...

Note also that aside from the concurrency argument, if your something else is another program (like more ), it must run in another process.另请注意,除了并发参数之外,如果您的其他程序是另一个程序(如more ),它必须在另一个进程中运行。 You create this process using fork .您使用fork创建此过程。 If you just run more in the current process (using exec ), it would replace your program.如果您只是在当前进程中运行more (使用exec ),它将替换您的程序。


In general, you can use a pipe without fork , but you'll just be communicating within your own process.通常,您可以在没有fork的情况下使用 pipe ,但您只会在自己的进程中进行通信。 This means you're either doing non-blocking operations (perhaps in a synchronous co-routine setup), or using multiple threads.这意味着您要么进行非阻塞操作(可能在同步协同程序设置中),要么使用多个线程。

You will find your answer precisely here你会在这里找到你的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM