Programs (such as vi
) which automatically adjust to screen resizing are responding to the SIGWINCH
signal, and using a system call to obtain the system's information about the screen-size. See for example Get width/height of a terminal window in c++?. By the way, though widely implemented, it does not appear to be documented in POSIX signal.h
.
Without taking SIGWINCH
into account, a program could ask the terminal about its screensize. The resize
program does this, by sending the terminal control sequences to
- move the cursor to the lower-right corner (actually, to row/column 999/999, which is good enough), and
- asking the terminal where the cursor really is.
The behavior of ls
and vi
(and other programs) regarding ANSI control sequences which would be embedded in their output depends upon the design of the program. They likely detect the redirection of their output to a file using the isatty
function, and do something different depending on whether the output is to a terminal, or to a file.