Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use select() to read input from keyboard in C

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?

like image 873
drum Avatar asked Jun 20 '11 22:06

drum


People also ask

What does select () do in C?

The select() function indicates which of the specified file descriptors is ready for reading, ready for writing, or has an error condition pending.

What is fd_ set in c?

FD_SET–Add a file descriptor to a file descriptor set This function adds a file descriptor to a file descriptor set.

How to take Standard input in c?

The scanf() and printf() Functionsfunction reads the input from the standard input stream stdin and scans that input according to the format provided. The int printf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided.

What is fd_ set in linux?

The fd_set data type represents file descriptor sets for the select function. It is actually a bit array. Macro: int FD_SETSIZE. The value of this macro is the maximum number of file descriptors that a fd_set object can hold information about. On systems with a fixed maximum number, FD_SETSIZE is at least that number.


1 Answers

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.).

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;
}
like image 144
luser droog Avatar answered Sep 20 '22 21:09

luser droog