jmClifford has asked for the wisdom of the Perl Monks concerning the following question:

Hi. I am wanting to do a non blocking type of read of the console input. I am trying to established a timed loop that performs as such that. The input response is only to indicate the operators wish to exit (the looping).

I am using Win 10 and Perl version 5.32.

From the web I get the following program as a possible approach;

use strict; use warnings; use Time::HiRes qw(usleep); print "start\n"; usleep(2000000); print "finish\n"; use Term::ReadKey; ReadMode 4; # Turn off controls keys 4 or "raw" my $key; while (not defined ($key = ReadKey(-1))) { # No key yet print "."; usleep(2000000); } print "Get key $key\n"; ReadMode 0; # Reset tty mode before exiting

The console output is;

start finish GetConsoleMode failed, LastError=|6| at C:/Strawberry/perl/vendor/lib/ +Term/ReadKey.pm line xxx.

The execution failure above is on ReadMode 4.

Are there any thoughts on why this failure occurs ?? I am surprised at the difficulty of achieving a non-blocking IO request and the lack of setting of say, a timeout of 0.

Regards JC.....

Replies are listed 'Best First'.
Re: Non blocking read from the console
by SankoR (Prior) on Oct 18, 2024 at 15:53 UTC

    Also works (im)perfectly fine on Windows 11 with both the command prompt (CMD) and Powershell.

    I decided to try running it in the most convoluted way I could think of and, as a subprocess of another app, I get the same message you reported. Are you running this in a way where the standard file handles are actually being piped to/from between a perl process and a pseudo-terminal?

      Hi. My console input (I suppose) is what ever comes with the Eclipse IDE software and uses Stawberry Perl.

      Regards JC....

        Try running it from the command prompt, not in the IDE's fake terminal.
Re: Non blocking read from the console
by hippo (Archbishop) on Oct 18, 2024 at 15:11 UTC
    I am using Win 10 and Perl version 5.32.

    I am using Linux and perl v5.34.0 and your code as given runs perfectly.


    🦛

Re: Non blocking read from the console
by Anonymous Monk on Oct 18, 2024 at 18:37 UTC
    I don't get where the non blocking part is ...
      the ReadKey(-1) (and the underlying system call) is non-blocking. At least OP doesn't hog the CPU as in the SYNOPSIS of Term::ReadKey, but uses usleep during the active waiting…