Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 18.12 Te rminal Window Size 711


•Other than storing the current value of the structureand generating a signal
when the value changes, the kernel does nothing else with this structure.
Interpreting the structure is entirely up to the application.

This featureisprovided to notify applications (such as thevieditor) when the window
size changes. When it receives the signal, the application can fetch the new size and
redraw the screen.

Example


Figure18.22 shows a program that prints the current window size and goes to sleep.
Each time the window size changes,SIGWINCHis caught and the new size is printed.
We have to terminate this program with a signal.
#include "apue.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)
err_sys("TIOCGWINSZ error");
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);
}

int
main(void)
{
if (isatty(STDIN_FILENO) == 0)
exit(1);
if (signal(SIGWINCH, sig_winch) == SIG_ERR)
err_sys("signal error");
pr_winsize(STDIN_FILENO); /* print initial size */
for ( ; ; ) /* and sleep forever */
pause();
}

Figure 18.22 Print window size
Free download pdf