【发布时间】:2011-10-01 12:30:52
【问题描述】:
int main(void)
{
char buf[] = "standard err, output.\n";
printf("standard output.\n");
if (write(STDERR_FILENO,buf, 22) != 22)
printf("write err!\n");
exit(0);
}
编译使用:
gcc -Wall text.c
然后在shell中运行:
-
./a.out > outfile 2 >& 1结果:outfile的内容是:
standard err, output. standard output. -
./a.out 2 >& 1 >outfile结果:
这首先打印到终端:
standard err, output.
而outfile的内容是:standard output.
问题:
我想问一下
2 >& fd和2 > file的区别。
它们都等于函数 dup() 吗?-
另一个问题:为什么outfile的内容是:
standard err, output. standard output.我预计 outfile 的内容是:
standard output. standard err, output
【问题讨论】:
-
“外壳”含糊不清;每个 shell 使用不同的语法。
-
顺便说一句,为什么要拨打
write()?要打印到标准错误,写fprintf(stderr, "whatever");要容易得多 -
@Wooble:不合格,“外壳”是指 POSIX 指定的外壳。
-
fd 号和 > 符号之间不应有任何空格。如果文件描述符编号后面有空格,则不会被识别,并将传递给命令(本例中为 a.out)