non-blocking read of stdin

Started by
3 comments, last by tariqwalji 13 years, 8 months ago
The Internet is saturated with wishy-washy non-answers to this question. Why is it such a convoluted problem?

Is there a way to read stdin in a non-blocking fashion?

I'd prefer a cross-platform solution, but I'm willing to hear out platform-specific solutions as well. I suppose another way to phrase the question would be like this: can I read raw keyboard input? Can I just check some kind of memory map indicating what keys are currently being pressed?

I use SDL for my graphical projects, and it provides a way to capture key events in a non-blocking manner. I'm working on a terminal app right now, and I'd rather not bring in SDL strictly for input event handlers. There has to be a simpler way...
Amateurs practice until they do it right.Professionals practice until they never do it wrong.
Advertisement
The only cross platform way of doing this is to use a library that is available on all your target platforms. But any platform of note provides a means to do this, from select() on *nix (or curses/ncurses) to conio.h on windows.
AFAIK there's no simple way for doing this. You have to reimplement the whole thing, and fit into your game loop somehow.

Basically you read the pressed key in case of a keypres event. The same way you'd do with arrow keys. If a key is pressed, you have to add it to the buffer, and probably add the terminating null to the end of it.

Try to look for "edit box implementation" or something like that in the forum search.

I think I misunderstood.

So you only want to check if a key is pressed, but don't wait if nothing is pressed?

Well, I'd go with SDL. If you use it anyway.


Well I'm not sure how stable this is, but under Linux you can just look at the particular device your keyboard is connected to under /dev/*.

Under Windows (particularly win32), you'd have to rely specifically on the Windows messaging service and use an array to flag whether a key is pressed on WM_KEYDOWN message.

You can probably give _inp() or something along those lines a shot. I believe (from other sources) the port number is 96.

Let me know how it goes!

This topic is closed to new replies.

Advertisement