Ncurses and stdin lock

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

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

I tried the installation nocbreak(), and it’s really great, except that nothing is displayed on the screen, so I don’t see what I’m typing. And the installation echo()does not change this.

I also tried using timeout(0), but the results of this were even crazier and didn't work.

+3
source share
1 answer

What you need to do is check if the character with the getch () function is available. If you use it in non-delay mode, the method will not be blocked. Then you need to eat the characters until you encounter "\ n", adding each char to the resulting string as you go.

Alternatively - and the method I'm using is to use the GNU readline library. It supports non-blocking behavior , but the documentation for this section is not so good.

Here is a small example that you can use. It has a selection loop and uses the GNU readline library:

#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;
}

Compile with:

gcc -Wall rl.c -lreadline
+1
source

Source: https://habr.com/ru/post/1722418/


All Articles