【问题标题】:How to write interactive program like Top? [closed]如何编写像Top这样的交互程序? [关闭]
【发布时间】:2023-03-21 05:49:01
【问题描述】:

当您运行top 时,您会进入一个位于终端中的交互式显示,但命令行已消失。

我想用这种类型的显示器构建一个程序,但我什至不知道要研究什么。

  • 我从哪里开始?

【问题讨论】:

  • 我认为你必须开始检查 vt100 控制字符的输出定位(ps.是的,ncurses)
  • 您可以查找 ncurses 或俚语库。它们为创建这种界面提供了构建块。
  • 我更新了我的答案以使用 bash shell 实现 top 的开始阶段。您可能想检查一下。

标签: shell terminal interactive


【解决方案1】:

top 在首次发布时使用了curses,但后来因为与 curses 相关的开销而切换到自己的屏幕管理代码。

更多关于top可以在以下链接阅读:


总的来说,您要查找的内容属于TUI(基于文本的用户界面)类别。


ncurses 通常是推荐给想要在终端中合并“图形”文本表示的人的 goto。

然而,有几种不同的选择,我建议谷歌找到一个合适的库供你使用。首先,您可以查看以下列出的链接:

【讨论】:

    【解决方案2】:

    出于教育目的,我提出了一个不完美但可用的程序,它可以捕获 bash 中的箭头键并立即响应它们:

    #!/bin/bash 
    
    # Put terminal into canonical mode with noecho 
    # (not required for this example but perhaps useful nonethless )
    MYTERMRESTORE=$(stty --save)
    stty icanon -echo
    
    # Obtain terminal dimensions 
    columns=$(tput cols)
    lines=$(tput lines)
    
    # Populate a buffer and store its size
    buffer="$(ps aux)"
    scroll="${#buffer}"
    
    # Set a top bar and scrolling region (printf "\033[2;${lines}")
    tput csr 1 "${lines}"
    while [ "${#x}" -lt "$columns" ]
    do x="$x="
    done
    printf "$x\n"
    
    # Set up a continuos loop
    while [ 1 ]
    do  printf "%.*s"  $scroll  "$buffer"
        printf "\n\nUse arrow keys to toggle through output, q to quit\n"
        read -n 1 i
        case "$i" in
            '[')
                 read  -n 1 j
                 case "$j" in
                      "A") # Up arrow
                           scroll=$(( scroll - $columns ))
                       ;;
                      "B") # Down arrow
                           scroll=$(( scroll + $columns ))
                       ;;
                 esac
                 ;;
            'q') break
                 ;;
        esac
    done
    
    
    stty "$MYTERMRESTORE"
    

    也许这个程序需要的最直接的改进是一种不断更新缓冲区的机制。在具有异步多路复用用户输入的程序中,这通常使用select() 来完成。

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2012-07-11
      • 2010-10-29
      相关资源
      最近更新 更多