How to make a pipe in c++

14,589

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

Solution 2

You will find your answer precisely here

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

Share:
14,589
node ninja
Author by

node ninja

Updated on June 15, 2022

Comments

  • node ninja
    node ninja almost 2 years

    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?

  • Bill the Lizard
    Bill the Lizard over 12 years
    While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.