In this lesson, you will learn how your shell detects and responds to changes in your terminal window's dimensions so that text layout remains consistent.
Understanding Viewport Geometry
When you resize your terminal window by dragging its corners, the terminal emulator does more than just show more or less blank space. It sends a specific signal to the foreground process—the shell or your application—notifying it that the number of rows and columns has changed. This is handled by the SIGWINCH (Signal Window Change) signal.
How the System Tracks Geometry
The kernel keeps track of the current window size within the terminal's line discipline settings. You can view these dimensions manually by running the stty size command, which returns the height (rows) and width (columns) as two integers.
When you resize the window, the terminal emulator updates the kernel’s internal structure and immediately dispatches SIGWINCH. If you are running a complex script, your process can "catch" this signal to re-calculate its display logic. For example, a dashboard script might listen for this signal to clear the screen and redraw its interface to fit the new boundaries.
Dynamic Layouts in Practice
You can observe this reaction in simple scripts using the trap command. Try running this in your terminal:
# Define a function to report new dimensions
function resize_handler() {
clear
echo "The window is now $(stty size)"
}
# Catch the SIGWINCH signal and call our function
trap resize_handler SIGWINCH
echo "Resize your window to see the update!"
Once you run this code, try dragging the window edges. Each time you stop resizing, the SIGWINCH signal triggers the handler, which runs stty size to pull the updated geometry from the kernel and reprints it. Without this signaling mechanism, your applications would be "blind" to their environment, resulting in garbled text or broken layouts whenever the viewport geometry changed.
Key Takeaway: The kernel broadcasts the SIGWINCH signal whenever your terminal window is resized, allowing processes to adjust their output layout to match the new character dimensions.