为什么 mawk 的输出(STDOUT)即使是终端也会被缓冲?

Why is mawk's output (STDOUT) buffered even though it is the terminal?

我知道 STDOUT 通常由 mawk(但不是 gawk)、grepsed 等命令缓冲,除非与适当的选项一起使用(即 mawk --Winteractive,或 grep --line-buffered,或 sed --unbuffered)。但是当 STDOUT 是 terminal/tty 时缓冲不会发生,在这种情况下它是行缓冲的。

现在,我不明白为什么 STDOUT 在发送到管道的循环之外被缓冲,即使最终目的地是终端。

一个基本的例子:

$ while sleep 3; do echo -n "Current Time is ";date +%T; done | mawk '{print $NF}'
^C

很长一段时间没有任何反应,因为 mawk 似乎在缓冲它的输出。

我没想到。 mawk的输出是终端,为什么它的STDOUT被缓冲了?

确实,使用 -Winteractive 选项输出每 3 秒渲染一次:

$ while sleep 3; do echo -n "Current Time is ";date +%T; done | mawk -Winteractive '{print $NF}'
10:57:05
10:57:08
10:57:11
^C

现在,此行为显然与 mawk 相关,因为如果我使用例如 grep,它不会重现。即使没有它的 --line-buffered 选项,grep 也不会缓冲它的 STDOUT,这是预期的行为,因为 grepSTDOUT 是终端 :

$ while sleep 3; do echo -n "Current Time is ";date +%T; done | grep Current
Current Time is 11:01:44
Current Time is 11:01:47
Current Time is 11:01:50
^C

我在这里得到了答案: https://unix.stackexchange.com/questions/655796/why-is-mawks-output-stdout-buffered-even-though-it-is-the-terminal#answer-655807

mawk 正在缓冲其输入,这让我感到困惑(另请参阅 https://github.com/ThomasDickey/original-mawk/issues/41#issuecomment-241070898

仔细阅读 mawk 的联机帮助页也给出了答案: -W interactive sets unbuffered writes to stdout and line buffered reads from stdin.