C 使用“运行时获取终端大小”;手表;在Linux中
我有一个简单的测试程序:C 使用“运行时获取终端大小”;手表;在Linux中,c,linux,terminal,C,Linux,Terminal,我有一个简单的测试程序: #include <stdio.h> #include <sys/ioctl.h> #include <unistd.h> #include <errno.h> #include <string.h> int main(int argc, char *argv[], char *envp[]) { struct winsize w; if (!ioctl(fileno(stdout), TIO
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[], char *envp[])
{
struct winsize w;
if (!ioctl(fileno(stdout), TIOCGWINSZ, &w)) {
printf("width %d\n", w.ws_col);
} else {
printf("%s", strerror(errno));
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[],char*envp[]
{
结构winsize w;
if(!ioctl(文件号(stdout)、TIOCGWINSZ和w)){
printf(“宽度%d\n”,w.ws\u col);
}否则{
printf(“%s”,strerror(errno));
}
返回0;
}
如果从终端本身运行,它将返回终端窗口的大小,但由于某种原因,如果通过watch
命令运行,它只会在ioctl()上失败,而ioctl()会返回不适当的设备ioctl
知道为什么吗?获取终端窗口大小的最可靠方法是什么?关键是,程序的stdout不再是终端,而是一个到
监视
的管道,它将收集并显示程序输出。因此,无法从标准输出文件描述符确定宽度
但是,stdin
仍然连接到终端,因此您可以使用fileno(stdin)
来获得正确的终端大小:
if (!ioctl(fileno(stdin), TIOCGWINSZ, &w)) {
printf("width %d\n", w.ws_col);
我建议你先检查一下。。。比如
isatty(fileno(stdout))
。我的猜测是,FILENO\STDOUT
(标准输出描述符)不是到终端,而是到管道。通常,stderr
是最好使用的文件流(描述符)。您还可以检查描述符后面的设备是否是终端-isatty()
,IIRC。