C选择()超时标准输入单个字符(无ENTER) [英] C select() timeout STDIN single char (no ENTER)

查看:149
本文介绍了C选择()超时标准输入单个字符(无ENTER)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用选择()从STDIN输入单个字符(无ENTER)上班。

I want to be able to use select() to work with entering a single char (no ENTER) from STDIN.

所以,当一个用户preSS一个键,选择()应立即返回,而不是等待用户敲击回车键。

So, when a user press a single key, select() should return immediately, not waiting for the user to hit 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);
}

这工作,但你必须按Enter键来完成。我只是想选择不等待用户打键和Enter键。

This works but you have to hit the ENTER key to finish. I just want the select not wait for the user to hit the key and ENTER.

感谢。

推荐答案

我相信,当钥匙进入终端,它的缓冲,直到你打回车,即只要程序而言,你没有输入任何东西。你可能想快速浏览一下在这个问题

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.

这篇关于C选择()超时标准输入单个字符(无ENTER)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆