gpt4 book ai didi

bash - bash中stdout和stderr的顺序

转载 作者:行者123 更新时间:2023-11-29 09:37:34 24 4
gpt4 key购买 nike

ls test.mp4  test.sh 1>/tmp/text  2>&1
cat /tmp/text
ls: cannot access test.sh: No such file or directory
test.mp4

为什么结果不是下面的顺序?

test.mp4
ls: cannot access test.sh: No such file or directory

可能1>/tmp/text先执行,test.mp4在test.sh之前执行。
结果是什么效果?

最佳答案

这与 bash 无关。它简单地反射(reflect)了 C 标准库 I/O 函数缓冲输出的方式。

这是Linux 系统上man setvbuf 的一段有用的摘录(解释主要来自C 和Posix 标准,但我认为在这段摘录中很容易找到和理解)。第二段是对您看到的行为的解释。

The three types of buffering available are unbuffered, block buffered, and line buffered. When an output stream is unbuffered, information appears on the destination file or terminal as soon as written; when it is block buffered many characters are saved up and written as a block; when it is line buffered characters are saved up until a newline is output or input is read from any stream attached to a terminal device (typically stdin). The function fflush(3) may be used to force the block out early. (See fclose(3).)

Normally all files are block buffered. If a stream refers to a terminal (as stdout normally does), it is line buffered. The standard error stream stderr is always unbuffered by default.

所以,回顾一下。 stdout 通常指的是终端,因此是行缓冲的,但您已将它重定向到一个文件,因此它是 block 缓冲的。但是,stderr 始终是无缓冲的,无论它是否已被重定向。

因此,打印到 stderr 的任何内容都会立即出现,而打印到 stdout 的任何内容都将保留,直到缓冲区填满(在 Linux 上,通常为 8kb)。

注意当 ls 检测到 stdout 不是终端时,它默认设置 -1 标志(每行一个文件名) .否则,它将默认设置 -x 标志(一行中可以容纳多少个文件名)。这意味着您将在终端上看到相同的反转,而根本没有任何重定向:

$ ls good bad
ls: cannot access bad: No such file or directory
good

关于bash - bash中stdout和stderr的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45316295/

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