Skip to content

Instantly share code, notes, and snippets.

@berk76
Last active February 16, 2021 10:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berk76/37df1ec10ef8e56458f87e58a67fa833 to your computer and use it in GitHub Desktop.
Save berk76/37df1ec10ef8e56458f87e58a67fa833 to your computer and use it in GitHub Desktop.
UNIX: Detecting terminal window resize

Detecting terminal window resize in UNIX

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment