[fpc-pascal] How to poll for a byte in Input?

Michael Van Canneyt michael at freepascal.org
Fri Dec 9 16:57:47 CET 2011



On Fri, 9 Dec 2011, tcoq wrote:

> Hello,
> I'm trying to poll the input stream to see whether there is a new character available, without blocking my software.
> I've tried "Read" and "THandleStream.ReadByte" but with no success: when the input is empty, the program just waits.
>
> Is there a way to ask whether the input stream is not empty, without waiting and without using threads/processes?
> And, in addition, is there an OS-independent way (linux, windows)?
>
> something like:
> var
>  inputStream: THandleStream;
>  aByte: Byte;
> begin
>  InputStream := THandleStream.Create(StdInputHandle);
>  try
>    while true do
>    begin
>      {$I-}
>      aByte := InputStream.ReadByte;
>      DoSomethingWithByte(aByte);
>      result := true;
>    end;
>  except
>    On E: EStreamError do result := false;
>  end;
>  //This code here is never executed
>  ThereIsNothingInInputStream_DoDefault;
> end;
>

You must use fpSelect() or Poll on the handle on linux/unix.
On windows, you'll need to WaitForObject() or so on the file handle.

Michael.



More information about the fpc-pascal mailing list