osm
osm

Reputation: 622

Is it possible to redirect stdout to two places in C?

I've been stuck on this for a while now, is it possible to redirect stdout to two different places? I am writing my own shell for practice, and it can currently run commands like ps aux | wc -l or ps aux | wc -l > output.file. However, when I try to run ps aux > file.out | wc -l, the second command does not receive the input from the first.

In the last example, the first command would be run in a child process that would output to one end of the pipe. The logic is similar to what follows:

close(stdout);
dup2(fd[1], STDOUT_FILENO);

//If a file output is also found
filewriter = open(...);
dup2(filewriter, STDOUT_FILENO);

//Execute the command

Upvotes: 3

Views: 507

Answers (2)

djhaskin987
djhaskin987

Reputation: 10097

The tee command does just that in UNIX. To see how to do it in straight C, why not look at tee's source code?

Upvotes: 2

JohnH
JohnH

Reputation: 2721

Normal UNIX shells don't work with that syntax either. UNIX (and some other OSs) provides the tee[1] command to send output to a file and also stdout.

Example: ps aux | tee file.out | wc -l

[1] See http://en.wikipedia.org/wiki/Tee_(command)

Upvotes: 3

Related Questions