Возможно, вы печатаете значение неинициализированной переменной. Ваш код не проверяет, успешно ли ioctl
, а если нет, он оставляет нетронутым ws
.
Fix:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
...
if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) {
fprintf(stderr, "can't get the window size of stdin: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
Когда вы передаете что-то в свою программу, stdin ссылается не на терминал, а на канал. Трубы не имеют размера окна. Вот почему TIOCGWINSZ
терпит неудачу здесь.
Портативное решение выглядит так:
const char *term = ctermid(NULL);
if (!term[0]) {
fprintf(stderr, "can't get the name of my controlling terminal\n");
exit(EXIT_FAILURE);
}
int fd = open(term, O_RDONLY);
if (fd == -1) {
fprintf(stderr, "can't open my terminal at %s: %s\n", term, strerror(errno));
exit(EXIT_FAILURE);
}
if (ioctl(fd, TIOCGWINSZ, &ws) == -1) {
fprintf(stderr, "can't get the window size of %s: %s\n", term, strerror(errno));
exit(EXIT_FAILURE);
}
close(fd);