如何在 c++ 中制作管道
我正在查看一个 C++ 程序的代码,该程序将文件的内容通过管道传输到 more。我不太明白,所以我想知道是否有人可以为 C++ 程序编写伪代码,将某些内容通过管道传输到其他内容?为什么需要使用fork?
I'm looking at the code for a c++ program which pipes the contents of a file to more. 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? Why is it necessary to use fork?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要
fork()
以便您可以在调用之前替换子进程的 stdin,并且这样您就不必等待进程再继续。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.您将在此处准确找到答案
You will find your answer precisely here
当您从外壳运行管道时,例如。
会发生什么? shell 运行两个进程(一个用于
ls
,一个用于more
)。此外,ls
的输出 (STDOUT) 通过管道连接到more
的输入 (STDIN)。请注意,
ls
和more
不需要了解有关管道的任何信息,它们只需分别写入(和读取)其 STDOUT(和 STDIN)。此外,由于它们可能会执行正常的阻塞读取和写入,因此它们能够并发运行至关重要。否则,在more
有机会消耗任何东西之前,ls
可能会填充管道缓冲区并永远阻塞。还要注意,除了并发参数之外,如果您的其他内容是另一个程序(例如
more
),那么它必须在另一个进程中运行。您可以使用fork
创建此进程。如果您只是在当前进程中运行more
(使用exec
),它将替换您的程序。一般来说,您可以使用没有
fork
的管道,但您只能在自己的进程内进行通信。这意味着您要么执行非阻塞操作(可能在同步协同例程设置中),要么使用多个线程。When you run a pipeline from the shell, eg.
what happens? The shell runs two processes (one for
ls
, one formore
). Additionally, the output (STDOUT) ofls
is connected to the input (STDIN) ofmore
, by a pipe.Note that
ls
andmore
don't need to know anything about pipes, they just write to (and read from) their STDOUT (and STDIN) respectively. Further, because they're likely to do normal blocking reads and writes, it's essential that they can run concurrently. Otherwisels
could just fill the pipe buffer and block forever beforemore
gets a chance to consume anything.Note also that aside from the concurrency argument, if your something else is another program (like
more
), it must run in another process. You create this process usingfork
. If you just runmore
in the current process (usingexec
), it would replace your program.In general, you can use a pipe without
fork
, but you'll just be communicating within your own process. This means you're either doing non-blocking operations (perhaps in a synchronous co-routine setup), or using multiple threads.