测试文件:
#include "apue.h"
int main()
{
char buffer[] = "adasdsxvxzv";
printf("hello,world!");
if (write(STDERR_FILENO, buffer, strlen(buffer)) < 0)
printf("error");
exit(0);
}
测试结果:
./hello >outfile 2>&1
cat outfile
adasdsxvxzvhello,world!
./hello 2>&1 > outfile
adasdsxvxzv
cat outfile
hello,world!
参考答案解释:
a.out > outfile 2>&1
首先设置标准输出到outfile,然后执行dup将标准输出复制到描述符2(标准错误)上,其结果是将标准输出和标准错误设置为相同的文件,即描述符1和2指向相同的文件表项。而对于命令行
a.out 2>&1 >outfile
由于首先执行dup,所以描述符2成为终端(假设命令是交互执行的),标准输出重定向到outfile。结果是描述符1指向outfile的文件表项,描述符2指向终端的文件表项。
./hello >outfile 2>&1的过程实际是:
open(outfile) == 3
dup2(3,1)
dup2(1,2)
./hello 2>&1 > outfile 的过程是:
dup2(1,2)
open(outfile) == 3
dup2(3,1)
该博客探讨了在Linux中使用'a.out > outfile 2>&1'命令行重定向时的标准输出和标准错误的处理。通过分析测试文件和参考答案,解释了如何通过dup系统调用使得标准输出和标准错误指向同一文件,并对比了不同重定向顺序的影响,指出在交互式执行中,描述符1和2可能指向不同的目的地。
1335

被折叠的 条评论
为什么被折叠?



