使用系统调用后重置(stty raw)

Reset after using system call (stty raw)

我正在使用下面的代码来读取和输出每个击键,而不必每次都按回车键。

system("\bin\stty raw");

在我读完之后,程序立即执行另一个系统调用来重置终端行为。

system("\bin\stty cooked");

问题是,最后一行没有按应有的方式重置终端行为。一旦该程序终止,一切都会变得一团糟。它继续读取输入,并且在按下 enter 或 CTRL C 或其他任何内容后不执行任何操作。

如何将终端行为重置为最初的行为?

使用popen()pclose()到运行"/bin/stty -g"。读取 stty -g] 的输出并保存以备后用。

当你想重置终端时,使用"/bin/stty the-string-from-stty-g"

机制很繁琐但可行。

stty-g 选项的全部意义在于提供一个可以传回 stty 以恢复当前设置的字符串。然后,您可以 运行 您的 stty raw,确保在退出之前使用 stty -g.

中的字符串重置终端

还要注意,stty sane 可以很好地将异常终端重置为已知状态。您可能需要 运行: Control-Jstty saneControl-J 在终端命令行使其工作.

您也可以在没有 运行 外部程序的情况下进行。您需要查看 tcgetattr()tcsetattr() and related functions. Again, you read the current settings (tcgetattr() et al), change a copy of them and set those as the new values, and ensure that you reset the original settings on exit (maybe with atexit()?).