Do not set COLS
and LINES
. These are managed by ncurses. Also, let ncurses reinitialize properly after a resize. That means, don't call wresize(). Just call endwin() instead. Make sure to call refresh() directly after an endwin() call before using other ncurses functions.
You also don't need the ioctl() at all. ncurses takes care of detecting the new size automatically.
So what you need is pretty much just an endwin() call:
void handle_winch(int sig)
{
endwin();
// Needs to be called after an endwin() so ncurses will initialize
// itself with the new terminal dimensions.
refresh();
clear();
mvprintw(0, 0, "COLS = %d, LINES = %d", COLS, LINES);
for (int i = 0; i < COLS; i++)
mvaddch(1, i, '*');
refresh();
}
Furthermore, some ncurses versions are configured to supply their own SIGWINCH handler. Those versions return KEY_RESIZE as a key input when a resize occurs. If you were to make use of that, you wouldn't need a signal handler at all. Instead, all you need is:
#include <ncurses.h>
#include <string.h>
int main()
{
initscr();
int key;
while ((key = getch()) != 27) {
if (key == KEY_RESIZE) {
clear();
mvprintw(0, 0, "COLS = %d, LINES = %d", COLS, LINES);
for (int i = 0; i < COLS; i++)
mvaddch(1, i, '*');
refresh();
}
}
endwin();
return 0;
}
Unfortunately, you can't rely on all ncurses installation being configured with KEY_RESIZE, so the signal handler is the most portable solution.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…