【问题标题】:how to show result dynamically in linux terminal? like 'top' command如何在linux终端中动态显示结果?像'top'命令
【发布时间】:2017-09-03 15:04:23
【问题描述】:

我想实现一个从可变文件中读取的 linux 命令,并且 每隔一秒动态地在终端中显示它。如何在linux终端中动态显示结果?像'top'命令?谢谢!

【问题讨论】:

  • 已经实现了。寻找watch 命令。
  • 谢谢@Arash,'watch' 可以帮助我。但是我想知道'top'和'watch'是如何工作的,这就是他们如何在终端中刷新输出,也许我应该看看他们的源代码。

标签: linux terminal command


【解决方案1】:

您可以使用watch 工具,如 man 中所述(Linux 在线 mans 位于 man7.org 站点):http://man7.org/linux/man-pages/man1/watch.1.html

   watch runs command repeatedly, displaying its output and errors (the
   first screenfull).  This allows you to watch the program output
   change over time.  By default, command is run every 2 seconds and
   watch will run until interrupted.

例如:

watch -n 1 tail -n 23 file

这将每 1 秒运行一次命令 tail -n 23 file(显示文件 file 的最后 25 行)(watch 的选项 -n 1)。 watch 将运行命令并打印其输出,休眠几秒钟,然后使用终端 (ANSI) 命令序列清除屏幕。 watch的实现有多种,最简单的在busybox包中:https://git.busybox.net/busybox/tree/procps/watch.c?h=1_17_stable

while (1) {
    /* home; clear to the end of screen */
    printf("\033[H""\033[J");
...
    fflush_all();
...
    system(cmd);
    sleep(period);
}

\033[H\033[J 序列可以清除屏幕(并且fflush_all 是just 自定义busybox 变体fflush(stdout))。 Linux 在console_codes (4) 手册页中记录了此类代码:http://man7.org/linux/man-pages/man4/console_codes.4.html\033 是 ESC,ESC [ 是 CSI,ECMA-48 CSI sequences 部分描述了 CSI H 和 CSI J 命令:

   ECMA-48 CSI sequences

   CSI ( or ESC [ ) is followed by a sequence of parameters .. An empty or
   absent parameter is taken to be 0.  The sequence of parameters may be
   preceded by a single question mark.

   H   CUP       Move cursor to the indicated row, column (origin at 1,1).
   J   ED        Erase display (default: from cursor to end of display).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-11
    • 2015-01-21
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多