1

Possible Duplicate:
Writing my own shell… stuck on pipes?

I'm building a program with shell like functionality, and I was wondering how to perform a piping operation. So when the system executes program1 arg | tee output-file the system will connect the stdin from the tee to the stdout from program1 as well as catching any stderr and the final stdout.

Community
  • 1
  • 1
topherg
  • 4,203
  • 4
  • 37
  • 72
  • it is, but is it going to be similar to c++ on unix, but I don't really see how to perform the piping operation in that question. – topherg Dec 07 '11 at 18:47
  • The code in the answers there should work fine as both C and C++, and on any Unixlike, including Linux, BSD, Mac OS, Solaris... – bdonlan Dec 07 '11 at 18:51
  • @bdonlan righto, im not sure how his function would be used within the rest of the program, would it run through the request string and split at the `|` points then run 1 in to 2, then 2 into 3 (if there were more than 2)? – topherg Dec 07 '11 at 18:55

1 Answers1

2

Ask for a pipe:

int p[2];
pipe(p);

Before the exec() of the first program, bind its standard output to it, and close the other fds:

dup2(p[0], STDOUT_FILENO);
close(p[0]);
close(p[1]);

Before the exec() of the second program redirect its standard input:

dup2(p[1], STDIN_FILENO);
close(p[0]);
close(p[1]);

You will also have to close both ends of the pipe in the master program after the fork()s, and you are done (for the pipe setup).