【问题标题】:How to have getc(stdin) to return ctrl characters?如何让 getc(stdin) 返回 ctrl 字符?
【发布时间】:2020-05-13 15:42:06
【问题描述】:

我正在尝试获取一个函数,该函数将返回从控制台读取的所有字符,包括 ctrl 字符,例如 ctrl-c。这都是在 linux 中使用 c++ 实现的。

但是它目前不返回 ctrl-c。我不确定是否有另一个终端设置允许这样做。

这是我目前正在使用的内容

int ttyGetChar() {
  struct termios newTerminalSettings;
  struct termios oldTerminalSettings;
  int result;

  tcgetattr(STDIN_FILENO, &oldTerminalSettings); // get old settings
  newTerminalSettings = oldTerminalSettings; // Copy to set up new settings

  newTerminalSettings.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newTerminalSettings); // Apply the new settings

  result = getc(stdin); // read one character under new settings
  tcsetattr(STDIN_FILENO, TCSANOW, &oldTerminalSettings); // Restore the old settings
  return result;
}

【问题讨论】:

  • 查看手册页,我想您可能想清除c_lflag 中的ISIG 位?
  • @NateEldredge 问题是我仍然需要生成信号。我在单独的代码中有一个信号处理程序,问题是我必须等待getc(stdin) 返回才能处理处理程序的结果。
  • 嗯,我不确定你能不能吃蛋糕也能吃。如果读取的字符是 Ctrl-C,你能清除 ISIG 然后手动 raise(SIGINT) 吗?

标签: c++ linux terminal termios


【解决方案1】:

这些不是字符,这些是控制事件。我相信 C++ 中没有“读取”它们的标准方法,但存在特定于平台的解决方案。例如,在 Windows 中,您有 SetConsoleCtrlHandler 函数来处理控制事件,而在 Linux 中,它们作为信号发送并且可以使用 signalsigaction 函数捕获。

【讨论】:

    猜你喜欢
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2012-12-18
    • 1970-01-01
    相关资源
    最近更新 更多