In this lesson, you will learn how your shell detects window resizing and why it needs a specific signal to keep your layout intact.
When you drag the corner of your terminal window to make it larger or smaller, the kernel needs a way to tell your running programs that the available "canvas" has changed dimensions. If your shell didn't know the window size had shifted, any text-based UI (like a text editor or a status bar) would eventually break, leaving behind visual artifacts or cutting off your command output.
The SIGWINCH Signal
When the terminal emulator (like GNOME Terminal or iTerm2) detects a change in the window geometry, it sends a signal called SIGWINCH (Signal Window Change) to the foreground process group.
Think of SIGWINCH as a "wake-up call." Because the shell is often responsible for drawing your prompt and managing the screen buffer, it must "catch" this signal to recalculate the new number of rows and columns. Without this signal, the shell would continue to assume the old dimensions, leading to a mismatch between where the cursor thinks it is and where it actually is on your screen.
Catching the Signal
In a script, you can instruct your shell to listen for this event. Here is a simplified look at how you might trap the signal to trigger a UI refresh:
# Define a function to refresh your UI components
refresh_ui() {
echo "Terminal resized! Recalculating layout..."
# Re-read columns and lines from the terminal environment
tput reset
}
# Trap the SIGWINCH signal and call the function
trap 'refresh_ui' SIGWINCH
When you execute this, the trap command sits quietly in the background. As soon as you resize your window, the kernel sends SIGWINCH, the trap interrupts whatever the shell is doing, executes your refresh_ui logic, and then returns control to your previous task. This ensures that your interface always remains responsive and aligned with the physical boundaries of your window.
Key Takeaway: The SIGWINCH signal acts as an interrupt that notifies the shell to re-query the terminal dimensions and redraw its UI components to prevent layout corruption.