C select() timeout STDIN single char (no ENTER)

假如想象 提交于 2019-11-30 22:52:19
Dan Fego

I believe, when a key is entered into the terminal, it's buffered until you hit ENTER, i.e. as far as the program is concerned, you haven't entered anything. You might want to take a quick look at this question.

In a Unix-style environment, this can be accomplished through the termios functions.

You need to disable canonical mode, which is the terminal feature that allows for line-editing before your program sees input.

#include <termios.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    /* Declare the variables you had ... */
    struct termios term;

    tcgetattr(0, &term);
    term.c_iflag &= ~ICANON;
    term.c_cc[VMIN] = 0;
    term.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &term);

    /* Now the rest of your code ... */
}

Catching the errors that could come from the tcgetattr and tcsetattr calls is left as an exercise for the reader.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!