手表在管道传输时切断 ps 辅助输出

MrL*_*mon 7 command-line grep pipe watch-command

在处理一个在这里无关紧要的(Python)脚本时,我遇到了一个非常奇怪的行为,涉及watchand ps aux,当后者通过管道传输到其他东西时。

我已经设法将问题减少到一行。跑步时

watch "ps aux | grep 'ps aux'"
Run Code Online (Sandbox Code Playgroud)

在终端中,正如预期的那样,您通常会得到几行输出。

输出显示 5 个结果

请注意,前三行被切断,ps aux最后几乎不适合。当您将终端的尺寸减小到不再适合的位置时,它会完全从结果中删除。

输出显示 2 个结果

这意味着 grep 只接收截止输出。我对此感到最困惑的是发生这种情况的范围极其有限。这不会发生在任何一个

ps aux | grep "ps aux"
watch "ps u -C ps"
watch "ssh localhost 'ps aux | grep \"ps aux\"'"
Run Code Online (Sandbox Code Playgroud)

在所有这些情况下,列表都按预期环绕。

在 Ubuntu 15.04 上,bash 和 sh 似乎都是这种情况。

虽然我设法在我的脚本中解决了这个问题,但有人对这种行为有任何解释吗?

mur*_*uru 6

鼻魔。1

man ps 说(强调我的):

comm       COMMAND   command name (only the executable name).
                     Modifications to the command name will not be
                     shown.  A process marked  is partly
                     dead, waiting to be fully destroyed by its
                     parent.  The output in this column may contain
                     spaces.  (alias ucmd, ucomm).  See also the args
                     format keyword, the -f option, and the c option.
                     When specified last, this column will extend to
                     the edge of the display.  If ps can not determine
                     display width, as when output is redirected
                     (piped) into a file or another command, the
                     output width is undefined (it may be 80,
                     unlimited, determined by the TERM variable, and
                     so on).  The COLUMNS environment variable or
                     --cols option may be used to exactly determine
                     the width in this case.  The w or -w option may
                     be also be used to adjust width.
Run Code Online (Sandbox Code Playgroud)

事实上,COLUMNS手动设置变量有助于:

watch "ps aux | grep 'ps aux'"
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

COLUMNS=2000 watch "ps aux | grep 'ps aux'"
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

1即使我们不是在谈论 C 编译器...