我在玩 termios
时发现,如果我更改终端设置并退出,我的更改将持续存在并破坏我的环境。因此,我设置了我的程序使用 tcgetattr
保存初始设置,并在退出之前重置它们。
然而,我预计,如果我在运行我的程序时按下 Ctrl-C
发送 SIGINT,那么它会导致终端仍然具有我的修改后的设置,因为我的程序不会执行代码将它们重新设置回旧设置。
但这没有发生。在 Ubuntu 和 macOS Sierra 中,我的终端设置被还原,就像我在程序中重置它们一样。
所以问题是:这种行为是否可以普遍依赖?或者在退出之前注册信号处理程序以捕获 SIGINT/SIGTERM 并恢复终端设置是否有意义?
代码
回答这个问题可能不需要查看代码,但以下是我的示例,以防您感兴趣:
#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;
}