I was playing around with termios
and I figured out quickly that if I change the terminal settings and exit, my changes will persist and screw up my environment. So I setup my program to save the initial settings with tcgetattr
and reset them before exiting.
I predicted, however, that if I hit Ctrl-C
to send SIGINT while my program was running that it would cause the terminal to still have my modified settings since my program wouldn't have executed the code to reset them back to the old settings.
But that didn't happen. In both Ubuntu and macOS Sierra, my terminal settings were reverted as if I had reset them in the program.
So the question is: Is this behavior something I can count on in general? Or does it make sense to register signal handlers to catch SIGINT/SIGTERM and revert terminal settings before exiting?
Code
Answering this question probably doesn't require looking at code, but here is my example, in case you're curious:
#include <stdio.h>
#include <string.h>
#include <termios.h>
int main() {
// put terminal into non-canonical mode
struct termios old;
struct termios new;
tcgetattr(0, &old);
new = old;
new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(0, TCSANOW, &new);
// loop: get keypress and display (exit via 'x')
char key;
printf("Enter a key to see the ASCII value; press x to exit.\n");
while (1) {
key = getchar();
printf("%i\n", (int)key);
if (key == 'x') { break; }
}
// set terminal back to canonical
tcsetattr(0, TCSANOW, &old);
return 0;
}