如何获取终端窗口宽度? [英] How to get terminal window width?
问题描述
我正在使用 C
和 linux
开发嵌入式系统.用户可以通过 SSH 或控制台串行电缆连接到设备.他可以通过 PuTTY 或 Tera Term 做到这一点.我的问题是,他连接后,我怎么知道他的窗口宽度?我尝试了不同的方法,如果我在 linux pc 上模拟我的系统,它们可以工作,但它们都不能在设备上工作:
I am working on embedded system using C
and linux
. User can connect to the device via SSH or a console serial cable. He can do this through PuTTY or Tera Term. My question is, after he is connected, how can I know his window's width? I have tried different approaches, they work if I simulate my system on a linux pc, but none of them work on the device:
ioctl()
struct winsize ws;
ioctl(..., TIOCGWINSZ, &ws);
此方法在pc上有效,但在设备上总是返回0.
This method works on pc, but it always returns 0 on the device.
tgetnum()
setupterm((char *)0, 1, (int *)0);
CGR_INT columns = tgetnum("co");
此方法适用于电脑,但在设备上总是返回 80x24.
This method works on pc, but it always returns 80x24 on the device.
getmaxyx()
CGR_INT xdim;
CGR_INT ydim;
initscr();
refresh();
getmaxyx(stdscr, ydim, xdim);
此方法在pc上有效,但在设备上总是返回0
This method works on pc, but it always returns 0 on the device
推荐答案
串口线没有办法协商终端的大小.运行一个真正的 xterm 等.通过 TTY/PTY 设备对使用 TIOCSWINSZ
/TIOCGWINSZ
ioctl()
对来传递此信息.
A serial line does not have a way to negotiate the size of the terminal. Running a real xterm et.al. over a TTY/PTY device pair uses the TIOCSWINSZ
/TIOCGWINSZ
ioctl()
pair to pass this information.
传统上,此信息保存在 termcap
或 terminfo
中,以了解真实的带荧光涂层的物理玻璃片终端(例如 DEC VT220).这是一个预先知道值的静态固定数据库,在终端"字面上是这个固定硬件的时候是正确的,但在终端只是一些程序的现代时代,它并不能很好地工作绘制到帧缓冲区或类似的.
Traditionally, this information was kept in termcap
or terminfo
about the real physical piece-of-glass-with-phosphor-coating terminals such as a DEC VT220. This is a static fixed database of values known ahead of time, which was correct around the time that a "terminal" literally was this fixed piece of hardware, but doesn't work so well in modern times of terminals being just some piece of program that draws to a framebuffer or similar.
我建议最好的方法是尝试 TIOCGWINSZ
,如果失败,请使用 terminfo
的 tgetnum("co")
,如果失败,则假设为 80x24.
I'd suggest the best method would be to try TIOCGWINSZ
, if that fails use terminfo
's tgetnum("co")
, and if that fails just presume 80x24.
这篇关于如何获取终端窗口宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!