现在的位置: 首页 > 综合 > 正文

APUE练习题3.5 – 文件重定向

2018年03月30日 ⁄ 综合 ⁄ 共 909字 ⁄ 字号 评论关闭

原题

3.5

The Bourne shell, Bourne-again shell, and Korn shell notation

     digit1>&digit2

says to redirect descriptor digit1 to the same file as descriptordigit2. What is the difference between the two commands

     ./a.out > outfile 2>&1
     ./a.out 2>&1 > outfile

(Hint: the shells process their command lines from left to right.)

大意就是问这两条命令的区别:

 ./a.out > outfile 2>&1
 ./a.out 2>&1 > outfile

关于重定向:

a.out > outfile:: 把a.out的标准输出重定向到文件outfile里面, > 为标准输出重定向符,默认重定向标准输出,即文件描述符1。

2>&1:把文件描述符2重定向到1对应的文件,相当于调用dup2(1, 2)

所以执行第一条命令的结果就是:

第一步:把1重定向到outfile,导致1指向outfile

第二部:把2重定向到1,所以2也指向outfile

第二条命令的执行结果是:

第一步:把2重定向到1对应的文件表,由于1初始状态是指向标准输出的,所以2也指向标准输出

第二部:把1重定向到outfile

写个程序测试一下:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

char s_stdin[]="stdin";
char s_stdout[]="stdout";

int main()
{
	write(1, s_stdin, sizeof(s_stdin)-1);
	write(2, s_stdout, sizeof(s_stdout)-1);
	return 0;
}

编译:gcc main.c,生成a.out

执行 ./a.out > outfile 2>&1,outfile里面内容为:stdinstdout,控制台无输出

执行 ./a.out 2>&1 > outfile,outfile里面内容为:stdin,控制台输出stdout

抱歉!评论已关闭.