我们知道,在UNIX shell中,&> outfile
将stdout
和stderr
重定向到outfile
.但是shell如何实现这一点呢?我写了一个天真的测试:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("tmpf", O_CREAT | O_TRUNC | O_WRONLY, 0644);
// redirect stdout to file
dup2(fd, 1);
close(fd);
// redirect stderr to stdout
dup2(2, 1);
close(2);
// print stuff to file
fprintf(stdout, "stdout string\n");
fprintf(stderr, "stderr string\n");
}
它只是将stdout
重定向到文件,然后将stderr
重定向到stdout
.但这不管用.上面的代码生成
$ ./a.out
stdout string
$ cat tmpf
$
如果我们交换stdout->file
和stderr->stdout
的顺序,结果如下
$ ./a.out
$ cat tmpf
stdout string
$