2006 06 22 15 52 kbhit() in the UNIX platform.

參考底下兩篇,結合起來的程式:
UNIX 的 getch()﹑kbhit()
BORLAND LINUX (KBHIT, Sleep etc)

========================================

#include <stdio.h>
#include <asm/ioctls.h>
#include <termios.h>
#include <unistd.h>

static struct termios initial_settings, new_settings;
static int peek_character = -1;

void init_keyboard()
{
    tcgetattr(0,&initial_settings);
    new_settings = initial_settings;
    new_settings.c_lflag &= ~ICANON;
    new_settings.c_lflag &= ~ECHO;
    new_settings.c_lflag &= ~ISIG;
    new_settings.c_cc[VMIN] = 1;
    new_settings.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &new_settings);
}

void close_keyboard()
{
    tcsetattr(0, TCSANOW, &initial_settings);
}

int kbhit()
{
    int n=0;
    ioctl(0, FIONREAD, &n);
    return n;
}

int kbhit2()
{
    unsigned char ch;
    int nread;

    if (peek_character != -1) return 1;
    new_settings.c_cc[VMIN]=0;
    tcsetattr(0, TCSANOW, &new_settings);
    nread = read(0,&ch,1);
    new_settings.c_cc[VMIN]=1;
    tcsetattr(0, TCSANOW, &new_settings);
    if(nread == 1)
    {
        peek_character = ch;
        return 1;
    }
    return 0;
}

int readch2()
{
    char ch;

    if(peek_character != -1)
    {
        ch = peek_character;
        peek_character = -1;
        return ch;
    }
    read(0,&ch,1);
    return ch;
}

int main()
{
    int i;
    int n=0;
    init_keyboard();
    printf("Enter 'n' to Stop it\n");
    for (i=0;;i++) {
//        printf("%d\n",i++);
        if (kbhit()) {
            n++;
            if(getchar()=='n') {
                break;
            }
        }
    }
    printf("n=%d\n",n);
    close_keyboard();
    return 0;
}