分页: 1 / 1

I/O重定向中提制标准错误的一个疑問

发表于 : 2011-06-11 1:46
shmily623
ls > file, 会将标准输出重定向到文件file
ls 1>&file, 将标准输出的文件描述符置为file的一个拷贝,这样的結果也导致ls的結果输出到文件file中
但是,执行ls 2>&file,时提示bash: file: ambiguous redirect. 而文件file中什么也没有。标准错误的文件描述符为什么不能置为文件file的描述符的一个拷贝?而标准输出就可以?

Re: I/O重定向中提制标准错误的一个疑問

发表于 : 2011-06-12 11:49
lexdene
好高深的问题啊!
帮你顶一下。

Re: I/O重定向中提制标准错误的一个疑問

发表于 : 2011-06-12 21:09
icyomik
我看了一下,也是想不明白,ls 0>&file也是错误,或者和文件描述符的相关定义冲突了吧,反正不明白为什么ls 1>&file可以。

Re: I/O重定向中提制标准错误的一个疑問

发表于 : 2011-06-12 21:16
lexdene
我到处搜了很久,也没有搜到相关的资料。

Re: I/O重定向中提制标准错误的一个疑問

发表于 : 2011-06-13 22:06
astolia
man bash的REDIRECTION一节里,有如下描述
Duplicating File Descriptors
The redirection operator

[n]<&word

is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of
that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to
-, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.

The operator

[n]>&word

is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits
in word do not specify a file descriptor open for output, a redirection error occurs. As a special case, if n is omitted, and word does not
expand to one or more digits, the standard output and standard error are redirected as described previously.
我从中没有看到任何word可以是文件名的描述,只说了word可以是1~2位数字或者是-。所以你用文件名当word应该是不正确的用法。
至于为什么1>&file能起效,我觉得是因为bash把1>&file和>&file做了等价处理,而>&file在man中的描述如下
Redirecting Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file
whose name is the expansion of word.

There are two formats for redirecting standard output and standard error:

&>word
and
>&word

Of the two forms, the first is preferred. This is semantically equivalent to

>word 2>&1
我写了个非常简单的程序进行验证

代码: 全选

$ cat a.c 
#include <stdio.h>

int main() {
	printf("xxx");
	while(1);
	return 0;
}

$ gcc a.c

$ ./a.out 1>&file &
[1] 12417

$ ls -l /proc/12417/fd/*
lrwx------ 1 xxx xxx 64 2011-06-13 22:02 /proc/12417/fd/0 -> /dev/pts/0
l-wx------ 1 xxx xxx 64 2011-06-13 22:02 /proc/12417/fd/1 -> /home/xxx/file
l-wx------ 1 xxx xxx 64 2011-06-13 22:02 /proc/12417/fd/2 -> /home/xxx/file
结果也证明了1>&file等价于>file 2>&1

如果需要直接的证据请自行阅读bash源代码

Re: I/O重定向中提制标准错误的一个疑問

发表于 : 2011-06-14 7:28
lexdene
楼上NB啊!