Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

unix

pipe

dup2

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
like image 632
n0shadow Avatar asked Dec 08 '25 09:12

n0shadow


1 Answers

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)

like image 192
JohnH Avatar answered Dec 09 '25 22:12

JohnH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!