【问题标题】:What is the best way to determine terminal height dynamically in C on Unix/Linux?在 Unix/Linux 上的 C 中动态确定终端高度的最佳方法是什么?
【发布时间】:2017-08-31 02:26:44
【问题描述】:

我想每 X 行显示一个标题,其中 X 使标题在最后一个滚动出屏幕时显示。用户可以改变终端尺寸,程序应该知道答案。大概是这样的

i = get_lines()+1;
while (1) {
    if (i > get_lines()) {
        printf("header");
        i = 0;
    } else {
        i++;
    }
    do_stuff();
}

【问题讨论】:

    标签: c linux unix terminal height


    【解决方案1】:

    您可以使用 TIOCGWINSZ 读取当前终端高度:

    #include <sys/ioctl.h> /* needed for lines */
    #include <signal.h>    /* needed for lines */
    #include <stdio.h>     /* needed for printf */
    #include <time.h>      /* needed for sleep */
    
    unsigned short lines;
    static void get_lines(int signo) {
        struct winsize ws;
        ioctl(fileno(stdout), TIOCGWINSZ, &ws);
        lines = ws.ws_row;
    }
    
    int main(int argc, char** argv) {
        int i;
        struct timespec ts;
    
        get_lines(SIGWINCH);
        signal(SIGWINCH, get_lines);
    
        i = lines;
        while (1) {
            if (i >= lines) {
                printf("header\n");
                i = 3; /* 3 not 1 because header + last empty line */
            } else {
                i++;
            }
            printf("line\n");
            ts.tv_sec = 0;
            ts.tv_nsec = 500000000;
            nanosleep(&ts, NULL);
        }
    }
    

    行数现在是ws.ws_row

    当用户更改终端大小(即调整其终端窗口大小)时,SIGWINCH 被发送到前台进程。所以你应该为这个事件建立一个信号处理程序并重新读取窗口大小。

    【讨论】:

    • 谢谢,这听起来正是我需要的。
    猜你喜欢
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多