内涵:对file descriptor、pipe操作符和redirect操作符等概念的记录

本文详细介绍了Linux指令中的文件描述符(如stdin、stdout、stderr)、管道操作符(|)和重定向操作符(>),以具体指令“g++ lots_of_errors 2>&1 > output.log”为例,解析了如何将错误输出重定向到标准输出,再将标准输出写入文件。理解这些概念有助于更好地控制命令行输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 引言

  本文是对linux指令中常涉及的(标准)file descriptor、pipe操作符和redirect操作符等概念的简单阐释。期待通过本文的撰写,对上述概念的认知从简单的复制、粘贴到略知其所以然的效果。

2. 工作场景

g++ lots_of_errors 2>&1 > output.log

  为了便于阐述,以对上述一条具体指令的含义阐述来彰显本文的主旨。

3. 正文

3.1 指令的拆分:command\pipe\redirect\file descriptor

  在该条指令中可以划分为4部分:

类别实例备注
command“g++ lots_of_errors”、“head”可执行程序
file descriptor“2” 、“&1”(标准)文件描述符
pipe operator“|”略(见下文)
redirect operator“>”略(见下文)

3.2 file descriptor

  file descriptro是一个非负的整数,用来表示文件的标识符。其中0, 1, 2三个数字是标准的file descriptor。

  • 0 is stdin
  • 1 is stdout
  • 2 is stderr
      当open一个普通的文件的时候,也会产生一个文件标识符file descriptor。例如,下文这段c语言代码中,fd就是file descriptor。
int main(int argc, char const *argv[])
{
 int fd;
 char buff[1000];
 
 if ((fd = open("file.txt",  O_RDONLY)) == -1)
 {
  printf("file opening failed\n");
  exit(0);
 }else{
  printf("file opening successful\n");
  printf("file descriptor: %d\n", fd);
 }
}

  而在python中open返回值一个称之未file object,事实上也是对file descriptor的高层的封装。

3.3 pipe operator

The Pipe is a command in Linux that lets you use two or more commands such that output of one command serves as input to the next. In short, the output of each process directly as input to the next one like a pipeline. The symbol ‘|’ denotes a pipe.

  也即‘|’可以连接多个command,将前一个command的输出作为下一个command的输入。

3.4 redirect operator

  redirect operator “>” 将command输出信息送入到一个文件中。

3.5 集中阐述

g++ lots_of_errors 2>&1 > output.log

  有了上述的认知,即可以对这一指令进行阐述:

  1. 首先’g++ lots_of_errors’ 会产生两个output stream: stdout(fd为2)和stderr(fd为1)。
  2. ‘2>&1’ 表示stderr的输出会打印到stdout上,可以认为是屏幕。
  3. '&1> output.log’表示stdout信息会存到output.log。[注意1]

  基于该指令就可以达到这样的效果:若程序运行出现error,则error信息会打印到屏幕上提醒运行者;若程序运行无error,则屏幕上无信息输出,程序运行中的正常log信息已经记录至log文件中。

4. 总结

  本文通过对“g++ lots_of_errors 2>&1 > output.log”这一指令的理解,对linux指令中常涉及的(标准)file descriptor、pipe操作符和redirect操作符等概念进行了阐述。为了不舍本逐末,暂时仅仅理解到不求甚解的程度即可。

5. 注意

[注意1]:file operator 1之所以需要添加一个&符号,是避免将其误认为一个文件的名称,起到一种类似转义的作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值