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:
- You execute
cat /dev/urandomor equivalent (for example,cat binary_file.dat). - Garbage is printed.
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:
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?

precmdhook?