zoukankan      html  css  js  c++  java
  • 一个常考重定向问题

    APUE 3.5关于重定向有个容易迷惑人的问题:

    ./a.out > outfile 2>&1

    ./a.out 2>&1 > outfile

    问两者区别。自己试了下,
      

    int main(){
           printf("output to stdio\n");
           fprintf(stderr,"output to stderr\n");
           return 1;
    }
    
    // 结果如下:
    $ ./a.out > outfile 2>&1
    $ cat outfile
    output to stderr
    output to stdin
    $ ./a.out 2>&1 > outfile
    output to stderr

      
      原因是:
      由于bash从左往右处理,在./a.out > outfile的时候,将a.out的fd 1定向到了outfile文件的fd上,然后才遇到2>&1,这时再将a.out的文件描述符2定向到文件描述符1上,这样stderr和stdout,就都到outfile上了。
      
      而下面一个则不然,先遇到2>&1,这时将a.out的文件描述符2定向到文件描述符1上,1是终端。再遇到 > outfile,这时将a.out的文件描述符1重定向到outfile这个文件。结果是,标准错误输出到了屏幕,而标准输出定向到了outfile!

      也可以写shell脚本测试一下:

      

    #!/bin/bash
    
    touch output
    
    test () {
        echo "before error.."
        someerror       #错误,变量或命令未定义
        echo "after error ..."
    }
    
    test  2>&1 >output
  • 相关阅读:
    WIN8.1安装 .net framework 3.5
    WIN8.1侧边栏文件夹删除
    初次接触Spring cloud微服务框架
    activiti中实现TaskListener注入Spring的bean
    spring中事务的回滚
    BeanUtils.copyProperties
    Java8新特性
    结构型模式总结
    创建型模式总结
    二十三种设计模式
  • 原文地址:https://www.cnblogs.com/zhaoyl/p/2733418.html
Copyright © 2011-2022 走看看