如何编写像Top一样的交互式程序?

4
当你运行 top 命令时,会进入一个交互式显示界面,它位于终端中,但命令行已经消失了。
我想要构建一个具有这种类型显示的程序,但我甚至不知道该研究什么。
  • 我应该从哪里开始?

2
ncurses:http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ - PeterMmm
我认为你必须开始检查vt100控制字符以进行输出定位(附注:是的,ncurses)。 - Leo
你可以寻找ncurses或slang库。它们提供了创建这种界面的基本构建块。 - Cong Ma
我更新了我的答案,使用bash shell实现了top的开始阶段。你可能想要查看一下。 - user4832408
2个回答

5

top最初使用curses,但由于与curses相关的开销较大,后来转而使用自己的屏幕管理代码。

有关top的更多信息可以在以下链接中阅读:


总体上,您所寻找的内容属于TUI(文本用户界面)类别。


通常情况下,ncurses是想要在终端中嵌入文本“图形”表示的推荐方法。

然而,还有其他几种选择,我建议您使用Google查找适合您使用的库。作为一个开始,您可以查看下面列出的链接:


3

为了教育目的,我提出了一个不完美但可用的程序,在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()来实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接