您的位置:首页 > 产品设计 > UI/UE

apue习题3.5 a.out > outfile 2>&1重定向问题

2017-08-20 17:48 260 查看
测试文件:

#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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: