终端在使用 termios 后进入非阻塞模式

问题描述

我想制作一个类似 ssh 的程序(用于练习),我需要使用 termios 才能立即获取密钥(无需等待用户按 Enter)

以下代码可以成功使输入无阻塞:

int NonBlockingMode() {
    struct termios options;
    if(tcgetattr(0,&options) == -1) {
        return -1;
    }

    options.c_lflag = options.c_lflag |
                                ~ICANON |
                                ~ECHO;
    options.c_cc[VMIN] = 0;
    options.c_cc[VTIME] = 1;

    if(tcsetattr(0,TCSANow,&options) == -1) {
        return -1;
    }

    int normal_flags = fcntl(0,F_GETFL,NULL);
    fcntl(0,F_SETFL,normal_flags | O_NONBLOCK);

    return 0;
}

但是我无法让它恢复正常。

我尝试了以下方法

int BlockingMode() {
    struct termios options;
    if(tcgetattr(0,&options) == -1) {
        return -1;
    }
    options.c_lflag = options.c_lflag |
                                ICANON |
                                ECHO;

    if(options.c_cc[VMIN] == 0)
    options.c_cc[VMIN] = 1;

    if(options.c_cc[VTIME] != 0)
    options.c_cc[VTIME] = 0;

    if (tcsetattr(0,normal_flags | ~O_NONBLOCK);

    return 0;
}

使用以下代码应该很容易找到问题:

int main() {
    std::string test;

    std::cin >> test;
    std::cout << std::endl << test << std::endl;
    BlockingMode();
    NonBlockingMode();

    // should be executed but in a non-blocking mode
    // you shouldn't be able to type anything
    test = "";
    std::cin >> test;
    std::cout << std::endl << test << std::endl;
}

执行此代码后,您将无法在终端中使用 CTRL-C

例如。通常在大多数终端中,当您按下 CTRL-C 时,它会显示一个 ^C 字符,您不应该看到这个字符

感谢任何帮助。

注意

当我跑步时有一条消息:readline: warning: turning off output flushing

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...