Shell之重定向

来源:互联网 发布:歼20鸭翼布局利弊知乎 编辑:程序博客网 时间:2024/04/28 06:58
        对于任何一个C程序,都对应有stdin, stdout, stderr这三种由C语言标准库定义的三个标准流。默认情况下,这三个流都指向终端,重定向(redirection)就是将这三种流重新指向其他位置。

        对stdin,stdout,stderr这三种流进行重定向的形式共有五种:

  • 将stdout重定向于stderr
  • 将stderr重定向于stdout
  • 将stdout重定向于文件
  • 将stderr重定向于文件
  • 将stdout和stderr重定向于同一个文件


       下面是一个简单的程序

        

#include<stdio.h>int main(int argc,char *argv[]){        fprintf(stdout,"This is an useless info sent to stdout.\n");        fflush(stdout);        fprintf(stderr,"This is an useless info sent to stderr.\n");        return 0;}

       第一种情况的写法为:

       ./main 1>&2

        输出结果为:

bash-4.2@redirection$ ./main 1>&2This is an useless info sent to stdout.This is an useless info sent to stderr.
      

       第二种情况的写法为:
       ./main 2>&1

       输出结果为:

This is an useless info sent to stdout.This is an useless info sent to stderr.
         

      第三种情况的写法为:

      ./main 1>outfile

      输出结果为:

bash-4.2@redirection$ ./main 1 > outfileThis is an useless info sent to stderr.bash-4.2@redirection$ cat outfileThis is an useless info sent to stdout.bash-4.2@redirection$ 
        

     第四中情况的写法为:

     ./main 2>errfile

     输出结果为:   

bash-4.2@redirection$ ./main 2>errfileThis is an useless info sent to stdout.bash-4.2@redirection$ cat errfileThis is an useless info sent to stderr.bash-4.2@redirection$ 

   

     第五种情况的写法为:

     ./main 2>errfile 1>&2

     或者是:

     ./main 1>outfile 2>&1

     输出结果为:

bash-4.2@redirection$ ./main 1>outfile 2>&1bash-4.2@redirection$ ./main 2>errfile 1>&2bash-4.2@redirection$ cat errfileThis is an useless info sent to stdout.This is an useless info sent to stderr.bash-4.2@redirection$ cat outfileThis is an useless info sent to stdout.This is an useless info sent to stderr.

原创粉丝点击