c – problem with a kbhit implementation – Education Career Blog

This is the kbhit implementation that I found, but for some reason it just waits a key to be pressed instead of returning some result other than 0. It doesn’t really function as kbhit…

int kbhit(void)
    struct timeval tv;
    fd_set read_fd;


    if(select(1, &read_fd, NULL, NULL, &tv) == -1)
        return 0;

        return 1;

    return 0;

Can anyone explain me what the problem is?
I’m using Linux, btw.

I think you might have misunderstood me, and thought that it actully returns non zero value after a key stroke.
my problem is that kbhit always WAITS for a key stroke.


stdin is probably line-buffered. You’ll need to switch it to unbuffered while trying to detect a keypress.

Leave a Comment