How can I flush unread data from a tty input queue on a UNIX system?

后端 未结 2 1317
礼貌的吻别
礼貌的吻别 2020-12-06 02:11

My program has to read just ONE character from the standard input, and so I use read(0, buffer, 1). But if the user insert more than one single character, they

2条回答
  •  臣服心动
    2020-12-06 03:03

    The POSIX answer is tcflush(): flush non-transmitted output data, non-read input data, or both. There is also tcdrain() which waits for output to be transmitted. They've been in POSIX since there was a POSIX standard (1988 for the trial-use version), though I don't recall ever using them directly.

    Example program

    Compile this code so the resulting program is called tcflush:

    #include 
    #include 
    #include 
    
    int main(void)
    {
        char buffer[20] = "";
    
        read(0, buffer, 1);
        printf("%c\n", buffer[0]);
        tcflush(0, TCIFLUSH);
        read(0, buffer, 1);
        printf("%c\n", buffer[0]);
        tcflush(0, TCIFLUSH);
        return 0;
    }
    

    Example dialog

    $ ./tcflush
    abc
    a
    def
    d
    $
    

    Looks like what the doctor ordered. Without the second tcflush(), the shell complains that it can't find a command ef. You can place a tcflush() before the first read if you like. It wasn't necessary for my simple testing, but if I'd used sleep 10; ./tcflush and then typed ahead, it would make a difference.

    Tested on RHEL 5 Linux on an x86/64 machine, and also on Mac OS X 10.7.4.

提交回复
热议问题