C non-blocking keyboard input

前端 未结 10 990
说谎
说谎 2020-11-22 05:59

I\'m trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn\'t require a keypress to continue each loop.

Is there a simple wa

10条回答
  •  时光说笑
    2020-11-22 06:31

    Here's a function to do this for you. You need termios.h which comes with POSIX systems.

    #include 
    void stdin_set(int cmd)
    {
        struct termios t;
        tcgetattr(1,&t);
        switch (cmd) {
        case 1:
                t.c_lflag &= ~ICANON;
                break;
        default:
                t.c_lflag |= ICANON;
                break;
        }
        tcsetattr(1,0,&t);
    }
    

    Breaking this down: tcgetattr gets the current terminal information and stores it in t. If cmd is 1, the local input flag in t is set to non-blocking input. Otherwise it is reset. Then tcsetattr changes standard input to t.

    If you don't reset standard input at the end of your program you will have problems in your shell.

提交回复
热议问题