Restore terminal output after exit program

Viewed 447

I have a small c program which uses the raw mode of the terminal. When I exit the program (and the raw mode), the terminal is cleared. Other programs like vim can handle that situation and restore the terminal output.

Is there a secret escape sequence or something to restore the terminal as it was before executing my program?

1 Answers

There's no need to do the restoration manually. Many applications like vim or less are using the concept called alternate screen, so check that. It exists exactly for such a purpose.

Simply switch to the alternate screen when your program starts and switch back right before it exits. You can use for example the following ANSI codes but there are more ways to achieve that:

  • switch to the alternate screen: \u001B[?1049h
  • switch from the alternate screen: \u001B[?1049l

See for example this answer for more details.

Related