简体   繁体   English

C select()超时STDIN单个字符(无ENTER)

[英]C select() timeout STDIN single char (no ENTER)

I want to be able to use select() to work with entering a single char (no ENTER) from STDIN. 我希望能够使用select()来处理从STDIN输入单个字符(无ENTER)。

So, when a user press a single key, select() should return immediately, not waiting for the user to hit ENTER. 因此,当用户按下单个键时, select()应立即返回,而不是等待用户按Enter键。

int main(void)
{
    fd_set rfds;
    struct timeval tv;
    int retval;

   /* Watch stdin (fd 0) to see when it has input. */
    FD_ZERO(&rfds);
    FD_SET(0, &rfds);

   /* Wait up to 2 seconds. */
    tv.tv_sec = 2;
    tv.tv_usec = 0;

   retval = select(1, &rfds, NULL, NULL, &tv);

   if (retval == -1)
        perror("select()");
    else if (retval)
        printf("Data is available now.\n");
    else
        printf("No data within five seconds.\n");

   exit(EXIT_SUCCESS);
}

This works but you have to hit the ENTER key to finish. 这有效,但您必须按ENTER键才能完成。 I just want the select not wait for the user to hit the key and ENTER. 我只想让select不等待用户按下键并按ENTER键。

Thanks. 谢谢。

I believe, when a key is entered into the terminal, it's buffered until you hit ENTER, ie as far as the program is concerned, you haven't entered anything. 我相信,当一个键进入终端时,它会被缓冲,直到你按下ENTER,即就程序而言,你没有输入任何东西。 You might want to take a quick look at this question . 您可能想快速查看这个问题

In a Unix-style environment, this can be accomplished through the termios functions. 在Unix风格的环境中,这可以通过termios函数来完成。

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. 捕获可能来自tcgetattrtcsetattr调用的错误留给读者练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM