The issue has nothing to do with PuTTY per se, and everything to do with SSH clients and pseudoterminals in general.
To avoid this issue, configure your PuTTY to use a pseudoterminal. (In the TTY panel, there is a "Don't allocate a pseudoterminal" checkbox. Make sure it is not checked.)
With ssh
, you need to use the -t
option to tell ssh
to use a pseudoterminal.
Here is a simple example program you can use in Linux to obtain the terminal size. It does not require curses:
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <stdio.h>
static int get_size(const int fd, int *const rows, int *const cols)
{
struct winsize sz;
int result;
do {
result = ioctl(fd, TIOCGWINSZ, &sz);
} while (result == -1 && errno == EINTR);
if (result == -1)
return errno;
if (rows)
*rows = sz.ws_row;
if (cols)
*cols = sz.ws_col;
return 0;
}
int main(void)
{
int rows, cols;
if (!get_size(STDIN_FILENO, &rows, &cols) ||
!get_size(STDOUT_FILENO, &rows, &cols) ||
!get_size(STDERR_FILENO, &rows, &cols))
printf("%d rows, %d columns\n", rows, cols);
else
fprintf(stderr, "Terminal size is unknown.\n");
return 0;
}
The actual information is obtained using the TIOCGWINSZ
TTY ioctl.
The pseudoterminal size is actually maintained by the kernel. If there is no pseudoterminal, just standard streams, there are no rows and columns; it's just a stream in that case. In particular, even tput lines
and tput cols
will fail then.
Many interactive command-line programs will refuse to work if there is no pseudoterminal. For example, top
will report something like "TERM environment variable not set" or "top: failed tty get". Others will work, just not interactively; they'll output once only, but as if the terminal was infinitely tall and infinitely wide.
In summary, your application should recognize whether it is running in a pseudoterminal (with terminal size known, curses support possible, and so on), or in stream mode (via SSH or PuTTY, deliberately without a pseudoterminal -- or perhaps just because inputs and outputs are all directed to/from files or some such).