如何使用select()读取键盘输入用C [英] How to use select() to read input from keyboard in C

查看:535
本文介绍了如何使用select()读取键盘输入用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用select()读取键盘输入和我被困在,我不知道如何从键盘读取并使用文件描述符这样做。我被告知要使用标准输入和STDIN_FILENO来解决这个问题,但我仍然感到困惑。结果
我该怎么办呢?

I am trying to use select() to read keyboard input and I got stuck in that I do not know how to read from keyboard and use a file descriptor to do so. I've been told to use STDIN and STDIN_FILENO to approach this problem but I am still confused.
How can I do it?

推荐答案

特殊照顾的问题听起来有点困惑。 选择()用来阻塞,直到输入可用。但是你做正常的文件读取功能的实际读数(如 FREAD 龟etc ,等等)。

Youre question sounds a little confused. select() is used to block until input is available. But you do the actual reading with normal file-reading functions (like read,fread,fgetc, etc.).

下面是一个简单的例子。它阻塞,直到有标准输入可用于读取至少一个字符。但是,当然,除非你改变终端的一些未煮过的模式,它阻止,直到你preSS输入,当输入的任何字符被刷新到文件缓冲区(一些终端缓存)。

Here's a quick example. It blocks until stdin has at least one character available for reading. But of course unless you change the terminal to some uncooked mode, it blocks until you press enter, when any characters typed are flushed into the file buffer (from some terminal buffer).

#include <stdio.h>
#include <sys/select.h>

int main(void) {
    fd_set s_rd, s_wr, s_ex;
    FD_ZERO(&s_rd);
    FD_ZERO(&s_wr);
    FD_ZERO(&s_ex);
    FD_SET(fileno(stdin), &s_rd);
    select(fileno(stdin)+1, &s_rd, &s_wr, &s_ex, NULL);
    return 0;
}

这篇关于如何使用select()读取键盘输入用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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