2

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;
}
Greg Schmit
  • 4,275
  • 2
  • 21
  • 36

1 Answers1

3

I was a bit surprised to see that in my Arch Linux terminal settings also "were reverted". But in fact they remained the same. When I changed your code I managed to track some anomaly.

//...
new.c_lflag &= ~(ICANON | ECHO);
new.c_cc[VMIN]  = 0;
new.c_cc[VTIME] = 0;
//...

So here if you don't press any button the output is -1. If you hit Ctrl-C, recompile and launch the original program (from the same terminal), it will also print -1, so there is no automatic reset.

I don't know why ECHO is "hidden" and I'd like to know, but I suggest you to manually revert all terminal settings.

vonaka
  • 913
  • 1
  • 11
  • 23
  • I couldn't reproduce the behavior you mentioned, but if it can be produced anywhere I think you're right that it makes sense to register a signal handler to reset terminal settings. Worst case scenario is you do a little extra work. – Greg Schmit Dec 16 '17 at 23:05