Jump to content

Keyboard input/Keypress check: Difference between revisions

→‎{{header|Perl}}: second possibility
(+perl)
(→‎{{header|Perl}}: second possibility)
Line 459:
until(defined($key = ReadKey(-1))){
# anything
sleep 1;
}
print "got key '$key'\n";
ReadMode 0('restore');</lang>
 
In many cases one does not want to wait for each step end. In this case you can use two parallel processes:
<lang perl>#!/usr/bin/perl
use strict;
use warnings;
use Carp;
use POSIX;
use Term::ReadKey;
$| = 1; # don't buffer; stdout is hot now
 
#avoid creation of zombies
sub _cleanup_and_die{
ReadMode('restore');
print "process $$ dying\n";
die;
}
sub _cleanup_and_exit{
ReadMode('restore');
print "process $$ exiting\n";
exit 1;
}
$SIG{'__DIE__'} = \&_cleanup_and_die;
$SIG{'INT'} = \&_cleanup_and_exit;
$SIG{'KILL'} = \&_cleanup_and_exit;
$SIG{'TERM'} = \&_cleanup_and_exit;
$SIG{__WARN__} = \&_warn;
 
# fork into two processes:
# child process is doing anything
# parent process just listens to keyboard input
my $pid = fork();
if(not defined $pid){
print "error: resources not available.\n";
die "$!";
}elsif($pid == 0){ # child
for(0..9){
print "doing something\n";
sleep 1;
}
exit 0;
}else{ # parent
ReadMode('cbreak');
# wait until child has exited/died
while(waitpid($pid, POSIX::WNOHANG) == 0){
my $seq = ReadKey(-1);
if(defined $seq){
print "got key '$seq'\n";
}
sleep 1; # if ommitted, the cpu-load will reach up to 100%
}
ReadMode('restore');
}</lang>
 
This code prints <code>"doing something"</code> 10 times and then ends. Parallelly another process prints every key you type in.
 
=={{header|Phix}}==
22

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.