【发布时间】:2020-01-13 13:38:14
【问题描述】:
我有这个简单的测试程序:
#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;
}
如果从终端本身运行,将返回终端窗口的大小,但由于某种原因,如果通过watch 命令运行,它只会在返回不合适的 IOCTL FOR DEVICE 的 ioctl() 上失败。
知道为什么吗?获取终端窗口大小的最可靠方法是什么?
【问题讨论】:
-
我建议你先检查
isatty...比如isatty(fileno(stdout))。我的猜测是FILENO_STDOUT(标准输出描述符)不会去终端,而是去管道。