How to get current size of terminal window and how to detect changes.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <termios.h>
#ifndef TIOCGWINSZ
#include <sys/ioctl.h>
#endif
static void pr_winsize(int fd) {
struct winsize size;
if (ioctl(fd, TIOCGWINSZ, (char *) &size) < 0) {
printf("TIOCGWINSZ error");
exit(1);
}
printf("%d rows, %d columns\n", size.ws_row, size.ws_col);
}
static void sig_winch(int signo) {
printf("SIGWINCH received\n");
pr_winsize(STDIN_FILENO);
if (signal(SIGWINCH, sig_winch) == SIG_ERR) {
printf("signal error");
exit(1);
}
}
int main(void) {
if (isatty(STDIN_FILENO) == 0)
exit(1);
if (signal(SIGWINCH, sig_winch) == SIG_ERR) {
printf("signal error");
exit(1);
}
pr_winsize(STDIN_FILENO); /* print initial size */
for ( ; ; ) /* and sleep forever */
pause();
}
Source:
Advanced Programming in the UNIX Environment
W. Richard Stevens
Stephen A. Rago