How to make a pipe in c++

2019-02-23 02:25发布

问题:

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?

回答1:

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.



回答2:

You will find your answer precisely here



回答3:

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.