检查是否已设置Termios结构

new9mtju  于 2022-10-04  发布在  iOS
关注(0)|答案(1)|浏览(132)

我编写了以下代码,以将终端设置为非规范模式:


# include <stdbool.h>

# include <stdio.h>

# include <stdlib.h>

# include <termios.h>

# include <unistd.h>

static struct termios old_terminal = {0};
static bool is_set = false;

static void restore_terminal(void) {
    tcsetattr(STDIN_FILENO, TCSANOW, &old_terminal);
}

static inline void configure_terminal(void) {
    if (!is_set) {
        tcgetattr(STDIN_FILENO, &old_terminal);
        struct termios new_terminal = old_terminal;
        new_terminal.c_lflag &= ~ICANON;  // Disable canonical mode
        new_terminal.c_lflag &= ~ECHO;    // Disable echo
        tcsetattr(STDIN_FILENO, TCSANOW, &new_terminal);
        atexit(restore_terminal);  // Even if the application crashes, the terminal must be restored
        is_set = true;
    }
}

我使用辅助变量is_set来保证,如果用户两次调用函数configure_terminal,它不会破坏终端。我的问题是:有没有办法删除变量is_set?对于INSTANTE,检查变量OLD_TERMINAL是否已设置?谢谢!

xghobddn

xghobddn1#

您可以首先调用tcgetattr以获取终端的当前模式,并检查ICANONECHO位的状态。

如果这些位已经被禁用,则不需要调用函数来禁用规范模式。测试可能如下所示:if (terminal.c_lflag & (ICANON | ECHO))...

相关问题