gpt4 book ai didi

c - 在Unix/Linux shell编程:the difference between > and >&

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:01:29 24 4
gpt4 key购买 nike

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中运行:

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

    结果:outfile的内容是:

    standard err, output.                
    standard output.
  2. ./a.out 2 >& 1 >输出文件

    结果:

    这首先打印到终端:standard err, output.
    outfile 的内容是:standard output.

问题:

  • 我想问一下2>&fd2>file的区别。
    它们都等于函数 dup() 吗?

  • 另一个问题:为什么outfile的内容是:

     standard err, output. 
    standard output.

    我预计 outfile 的内容是:

     standard output. 
    standard err, output

最佳答案

实际上,在 bash 中,>&dup2 非常相似。也就是说,它所应用的文件描述符将引用与右侧描述符相同的文件。所以:

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

它将 stdout(1) 重定向到文件 outfile,之后,dup2 stderr(2) 将引用与 stdout(1) 相同的文件。也就是说,stdout 和 stderr 都被重定向到文件。

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

它将重定向 stderr(2) 以引用与 stdout(1) 相同的文件,即控制台,之后,将重定向 stdout(1) 以引用文件 outfile。也就是说,stderr 将输出到控制台,stdout 将输出到文件。

这正是您得到的。

关于c - 在Unix/Linux shell编程:the difference between > and >&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7620217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com