How to make a pipe in c++

孤街浪徒 提交于 2019-12-01 17:49:44
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.

You will find your answer precisely here

Why is it necessary to use fork?

When you run a pipeline from the shell, eg.

$ ls | more

what happens? The shell runs two processes (one for ls, one for more). Additionally, the output (STDOUT) of ls is connected to the input (STDIN) of more, by a pipe.

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. 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.

... 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. You create this process using fork. If you just run more in the current process (using exec), 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!