Unix/Linux 在 C 中动态确定终端高度的最佳方法是什么?

What is the best way to determine terminal height dynamically in C on Unix/Linux?

我想每 X 行显示一个 header,其中 X 使 header 在最后一行滚出屏幕时出现。用户可以改变终端尺寸,程序应该知道答案。大致像

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

您可以使用 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

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