Search code examples
cidle-timer

C detect user typing characters in stdin


Is it possible to detect whether a user is simply typing anything into stdin?

man select says:

select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible).

I guess "ready" means EOF or NL. But what about single characters? Could you program a timer-callback in C, which starts when the user has been idle for some seconds? If yes, how?


Solution

  • Yes, this is possible, but you have to put your terminal into character mode. By default, programs usually start in line mode, where your program doesn't get notified for input until a whole line was entered.

    You should use a library like for example ncurses to put your terminal into character mode, for example with

    initscr();
    cbreak();
    

    Now, if you select() your standard input, you will be notified for each character entered, which you can retrieve with getch().

    For more details, the NCURSES Programming HowTo might help.

    Edit on request of the OP:

    If you just have to support linux, you would set the appropriate options in the terminal configuration.

    First, read in the current parameters:

    struct termios config;
    tcgetattr(0, &config);
    

    Then, switch canonical (line mode) off:

    config.c_lflag &= ~ICANON;
    

    and specify, that a single character suffices to return from read:

    config.c_cc[VMIN] = 1;
    

    Finally, set these parameters on your stdin terminal:

    tcsetattr(0, TCSANOW, &config);
    

    Now, a read() should return on a single character read.