0

Is there a portable way to read data from stdin without blocking, or to check if data is available to be read without blocking? Keep in mind stdin could be piped from another process, not just be terminal/keyboard input.

Best would be only using ANSI C function from stdlib.h or stdio.h, but using POSIX functions would be very portable too.

Also I'm not sure about this, but there are some forum posts where they say select() wouldn't work on Windows in practice.

sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • could you mention the cause or your case I never get the scanf blocked – MOHAMED Jan 11 '13 at 13:38
  • I recall something about peek and found this through a bit of googling, might be something there that works. http://www.velocityreviews.com/forums/t318260-peek-at-stdin-flush-stdin.html – dutt Jan 11 '13 at 13:45
  • http://stackoverflow.com/questions/8101079/making-stdin-non-blocking –  Jan 11 '13 at 13:49

1 Answers1

5

select() and poll() are the POSIX way, but they won't work on Windows for non-sockets.

If Windows and Unix are both your targets, there's no way portable enough. Even more, on Windows you have to handle pipes and console handles separately: PeekNamedPipe() for pipes, PeekConsoleInput() for console (and it's rather complicated with the latter even if you don't have ENABLE_LINE_INPUT, turning to a real can of worms if you do).

Doing input in a separate thread is more portable, even with pthread vs. Windows differences (and there are pthread-for-Win32 libraries to get rid of those differences).

Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69