Linux下如何在C#终端程序中禁用非预期用户输入
解决Linux下.NET程序运行时终端可输入回显的问题
问题出在终端的默认工作模式:Linux终端默认处于「规范模式(canonical mode)」,输入会由终端驱动缓存,直到按下换行键才会传递给程序;同时终端默认开启「回显(echo)」,输入的字符会直接显示在屏幕上——这两种行为是终端自身的设置,和你的.NET程序是否读取输入流无关,所以单纯关闭.NET的输入输出流不会生效。
下面是两种可靠的解决方案:
方法1:通过stty命令控制终端状态
stty是Linux下用于配置终端的命令,可以直接禁用回显和规范模式,程序退出时再恢复原始设置。
示例代码
using System; using System.Diagnostics; class Program { static void Main(string[] args) { // 保存终端原始设置,用于退出时恢复 var saveProc = new Process { StartInfo = new ProcessStartInfo { FileName = "stty", Arguments = "--save", RedirectStandardOutput = true, UseShellExecute = false } }; saveProc.Start(); string originalSettings = saveProc.StandardOutput.ReadToEnd().Trim(); saveProc.WaitForExit(); try { // 禁用回显和规范模式:输入不会回显,也不会缓存到换行 var disableProc = new Process { StartInfo = new ProcessStartInfo { FileName = "stty", Arguments = "-echo -icanon", UseShellExecute = false } }; disableProc.Start(); disableProc.WaitForExit(); // 你的业务逻辑(示例为无限循环) while (true) { System.Threading.Thread.Sleep(1000); } } finally { // 强制恢复终端原始设置,避免程序异常退出后终端状态异常 var restoreProc = new Process { StartInfo = new ProcessStartInfo { FileName = "stty", Arguments = originalSettings, UseShellExecute = false } }; restoreProc.Start(); restoreProc.WaitForExit(); } } }
方法2:通过P/Invoke调用libc的终端控制API
如果不想依赖外部stty命令,可以直接调用Linux系统的termios API,直接操作终端属性,这种方式更底层、更可靠。
示例代码
using System; using System.Runtime.InteropServices; class Program { // 定义Linux终端属性结构体 [StructLayout(LayoutKind.Sequential)] private struct Termios { public const int ICANON = 0x0002; // 规范模式标志位 public const int ECHO = 0x0008; // 回显标志位 public int c_iflag; public int c_oflag; public int c_cflag; public int c_lflag; public int c_line; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] c_cc; } // 导入libc的终端属性读取函数 [DllImport("libc", SetLastError = true)] private static extern int tcgetattr(int fd, ref Termios termios); // 导入libc的终端属性设置函数 [DllImport("libc", SetLastError = true)] private static extern int tcsetattr(int fd, int optional_actions, ref Termios termios); private const int STDIN_FILENO = 0; // 标准输入文件描述符 private const int TCSANOW = 0; // 立即应用终端设置 static void Main(string[] args) { Termios originalTermios = new Termios(); // 读取当前终端属性 tcgetattr(STDIN_FILENO, ref originalTermios); try { Termios newTermios = originalTermios; // 关闭规范模式和回显:清除对应标志位 newTermios.c_lflag &= ~(Termios.ICANON | Termios.ECHO); // 应用新的终端设置 tcsetattr(STDIN_FILENO, TCSANOW, ref newTermios); // 你的业务逻辑(示例为无限循环) while (true) { System.Threading.Thread.Sleep(1000); } } finally { // 强制恢复原始终端属性 tcsetattr(STDIN_FILENO, TCSANOW, ref originalTermios); } } }
注意事项
- 无论用哪种方法,都必须在程序退出时恢复终端原始设置,否则终端会处于无回显、无规范模式的异常状态。如果出现这种情况,直接在终端执行
stty sane即可快速恢复正常。 - 测试时如果程序陷入无限循环,可以用
Ctrl+C终止,finally块会自动执行恢复操作。
内容的提问来源于stack exchange,提问作者Marvin Marjan
相关产品推荐
相关产品推荐

