ncurses 和 stdin 阻塞

2023-12-10

I have stdin in a select() set and I want to take a string from stdin whenever the user types it and hits Enter.

But select is triggering stdin as ready to read before Enter is hit, and, in rare cases, before anything is typed at all. This hangs my program on getstr() until I hit Enter.

我尝试设置nocbreak()它真的很完美,只是屏幕上没有任何回声,所以我看不到我正在输入的内容。和设置echo()并没有改变这一点。

我也尝试过使用timeout(0),但结果更疯狂,不起作用。


您需要做的是通过 getch() 函数检查字符是否可用。如果您在无延迟模式下使用它,该方法将不会阻塞。然后,您需要吃掉这些字符,直到遇到“\n”,然后将每个字符附加到结果字符串中。

另外,我使用的方法是使用 GNU readline 库。它支持非阻塞行为,但是有关该部分的文档并不是那么出色。

这里包含一个您可以使用的小示例。它有一个选择循环,并使用 GNU readline 库:

#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdlib.h>
#include <stdbool.h>

int quit = false;

void rl_cb(char* line)
{
    if (NULL==line) {
        quit = true;
        return;
    }

    if(strlen(line) > 0) add_history(line);

    printf("You typed:\n%s\n", line);
    free(line);
}

int main()
{
    struct timeval to;
    const char *prompt = "# ";

    rl_callback_handler_install(prompt, (rl_vcpfunc_t*) &rl_cb);

    to.tv_sec = 0;
    to.tv_usec = 10000;

    while(1){
        if (quit) break;
        select(1, NULL, NULL, NULL, &to);
        rl_callback_read_char();
    };
    rl_callback_handler_remove();

    return 0;
}

编译:

gcc -Wall rl.c -lreadline
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ncurses 和 stdin 阻塞 的相关文章