How to prevent random console output from breaking the terminal

escape-charactersoutputterminal

There are many questions on SE that show how to recover from terminal broken by cat /dev/urandom. For those that are unfamiliar with this issue – here what it is about:

  1. You execute cat /dev/urandom or equivalent (for example, cat binary_file.dat).
  2. Garbage is printed.
  3. That would be okay… except your terminal continues to print garbage even after the command has finished! Here's a screenshot of a misrendered text that is in fact g++ output:

    Example screenshot

    I guess people were right about C++ errors sometimes being too cryptic!

The usual solution is to run stty sane && reset, although it's kind of annoying to run it every time this happens.

Because of that, what I want to focus on in this question is the original reason why this happens, and how to prevent the terminal from breaking after such command is issued. I'm not looking for solutions such as piping the offending commands to tr or xxd, because this requires you to know that the program/file outputs binary before you actually run/print it, and needs to be remembered each time you happen to output such data.

I noticed the same behavior in URxvt, PuTTY and Linux frame buffer so I don't think this is terminal-specific problem. My primary suspect is that the random output contains some ANSI escape code that flips the character encoding (in fact, if you run cat /dev/urandom again, chances are it will unbreak the terminal, which seems to confirm this theory). If this is right, what is this escape code? Are there any standard ways to disable it?

Best Answer

No:

  • there is no standard way to "disable it", and
  • the details of breakage are actually terminal-specific, but
  • there are some commonly-implemented features for which you can get misbehavior.

For commonly-implemented features, look to the VT100-style alternate character set, which is activated by ^N and ^O (enable/disable). That may be suppressed in some terminals when using UTF-8 mode, but the same terminals have ample opportunity for trashing your screen (talking about GNU screen, Linux console, PuTTY here) with the escape sequences they do recognize.

Some of the other escape sequences for instance rely upon responses from the terminal to a query (escape sequence) by the host. If the host does not expect it, the result is trash on the screen.

In other cases (seen for instance in network devices with hardcoded escape sequences for the Linux console), other terminals will see that as miscoded, and seem to freeze.

So... you could focus on just one terminal, prune out whatever looks like a nuisance (as for instance, some suggest removing the ability to use the mouse for positioning in editors), and you might get something which has no apparent holes. But that's only one terminal.

Related Question