3

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
4

2 回答 2

4

普通的 UNIX shell 也不适用于该语法。UNIX(和其他一些操作系统)提供tee[1] 命令来将输出发送到文件,并且还提供stdout.

例子: ps aux | tee file.out | wc -l

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

于 2014-07-17T14:40:06.997 回答
2

tee命令在 UNIX 中就是这样做的。要了解如何在直接 C 中执行此操作,为什么不查看tee 的源代码

于 2014-07-17T14:45:31.497 回答