大家。我对编程还是新手。我确实需要一些帮助来解决我面临的问题。所以,这里的情况是我试图在终端尺寸低于 80x24 时显示警告。根据记录,我的操作系统是 Window,但我使用虚拟机来运行 Linux,因为所有文件都在 Linux 中。当我使用终端运行文件时,警告显示正确。但问题是当我尝试使用 PuTTY 从 Windows 运行该文件时。警告没有出现。我确定是因为我使用的函数只能读取Linux环境,而不能读取Windows环境。任何人都可以帮助我或为我指出如何使其能够获取 window 尺寸的方向。这些文件应该全部保留在 Linux 中。我正在使用 C。
这里只是展示有关显示警告和获取尺寸的代码的一部分。
//This is to display warning
int display_warning()
{
CDKSCREEN *cdkscreen = 0;
WINDOW *cursesWin = 0;
char *mesg[5];
char *buttons[] = {"[ OK ]"};
CDKDIALOG *confirm;
cursesWin = initscr();
cdkscreen = initCDKScreen (cursesWin);
initCDKColor();
mesg[0] = "</2>"The size of Window must be at least 80x24.";
confirm = newCDKDialog(cdkscreen, CENTER, CENTER, mesg, 1, buttons, A_REVERSE, TRUE,TRUE, FALSE);
setCDKDialogBackgroundColor(confirm, "</2>");
injectCDKDialog(confirm,TAB);
activateCDKDialog(confirm,0);
if (confirm -> exitType == vNORMAL){
destroyCDKDialog (confirm);
destroyCDKScreen (cdkscreen);
endCDK();
}
return 0;
}
//This is to get the dimension
int get_terminal_size()
{
int cols;
int lines;
#ifdef TIOCGSIZE
struct ttysize ts;
ioctl(0,TIOCGSIZE, &ts);
lines = ts.ts_linesl;
cols = ts.ts_cols;
#elif defined(TIOCGWINSZ)
struct winsize ts;
ioctl(0, TIOCGWINSZ, &ts);
lines = ts.ws_row;
cols = ts.ws_col;
#endif
if((lines <= 23)||(cols <= 79)){
display_warning();
}
return 0;
}
//then there will be the main function that i think is not necessary to put the code here.
非常感谢所有评论和帮助。我是编程初学者,所以如果有一些基本的东西我不知道,请原谅。
菲克里
最佳答案
该问题与 PuTTY 本身无关,与一般的 SSH 客户端和伪终端有关。
要避免此问题,请将 PuTTY 配置为使用伪终端。 (在 TTY 面板中,有一个“不分配伪终端”复选框。请确保未选中它。)
使用ssh
,您需要使用-t
选项告诉ssh
使用伪终端。
这是一个简单的示例程序,您可以在 Linux 中使用它来获取终端大小。它不需要诅咒:
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <stdio.h>
static int get_size(const int fd, int *const rows, int *const cols)
{
struct winsize sz;
int result;
do {
result = ioctl(fd, TIOCGWINSZ, &sz);
} while (result == -1 && errno == EINTR);
if (result == -1)
return errno;
if (rows)
*rows = sz.ws_row;
if (cols)
*cols = sz.ws_col;
return 0;
}
int main(void)
{
int rows, cols;
if (!get_size(STDIN_FILENO, &rows, &cols) ||
!get_size(STDOUT_FILENO, &rows, &cols) ||
!get_size(STDERR_FILENO, &rows, &cols))
printf("%d rows, %d columns\n", rows, cols);
else
fprintf(stderr, "Terminal size is unknown.\n");
return 0;
}
实际信息是使用TIOCGWINSZ
TTY ioctl 获取的。
伪终端大小实际上由内核维护。如果没有伪终端,只有标准流,就没有行和列;在这种情况下它只是一个流。特别是,即使 tputlines
和 tputcols
也会失败。
如果没有伪终端,许多交互式命令行程序将无法运行。例如,top
将报告类似“TERM 环境变量未设置”或“top: failed tty get”的信息。其他的也可以,只是不能交互;它们只会输出一次,但就好像终端无限高无限宽一样。
总之,您的应用程序应该识别它是在伪终端中运行(终端大小已知,可能支持诅咒等),还是在流模式下运行(通过 SSH 或 PuTTY,故意不使用伪终端——或者也许只是因为输入和输出都定向到/来自文件或类似的文件)。
关于c - 如何从 Linux 获取窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783988/