1754314 Members
2657 Online
108813 Solutions
New Discussion юеВ

Timeout getchar() in C

 
SOLVED
Go to solution
Renda Skandier
Frequent Advisor

Timeout getchar() in C

Hi,
I have a program receiving one character at a time. If nothing is entered for 5 min, I'd like to break out of the loop.
something like
while (time(&curtime) - lastsendtime) < 300 )
getchar();

unfortunately, this doesn't get to my time check until a char is entered
Any ideas?
tia
3 REPLIES 3
Dennis Handly
Acclaimed Contributor
Solution

Re: Timeout getchar() in C

Perhaps you should just use alarm(2)?
Otherwise you would have to use select(2) and system calls.

#include
#include
#include
void got_alarm(int sig) {
fprintf(stderr, "Got signal %d\n", sig);
}
int main() {
alarm(5*60);
signal(SIGALRM, got_alarm);
int c = getchar();
printf("getchar returned %x\n", c);
return 0;
}

Before you get each char, you would have to reenable the alarm. While not reading, you would have to disable it.
James R. Ferguson
Acclaimed Contributor

Re: Timeout getchar() in C

Hi Renda:

Sending 'alarm()' to SIGALRM works nicely in Perl too when using 'getc()':

Consider this script where I'va added the appropriate signal handler (SIGALRM) and 'alarm()' call to timeout a character read (getc()) after 5-seconds.

The Term::ReadKey Perl module is a compiled C module that offers control over various terminal modes.

#!/usr/bin/perl
use strict;
use warnings;
use Term::ReadKey;
$SIG{HUP} = 'IGNORE';
$SIG{INT} = 'IGNORE';
$SIG{QUIT} = 'IGNORE';
$SIG{ALRM} = sub { ReadMode 'restore'; print STDERR "\nTIMEOUT!\n"; exit 0 };
$SIG{TERM} = sub { ReadMode 'restore'; exit 0 };
my $char;
my @password;
my $tmout = 0; #...ARBITRARY...set to 0 to disable...
print "Enter password: ";
ReadMode 'noecho';
ReadMode 'raw';
alarm $tmout;
while ( $char = ReadKey 0 ) {
last if $char eq "\n";
next if ( ord($char) < 040 or ord($char) > 0176 );
push( @password, $char );
print '*';
alarm $tmout;
}
ReadMode 'restore';
print "\n>", @password, "<\n";
1;
#_jrf.

Regards!

...JRF...
Renda Skandier
Frequent Advisor

Re: Timeout getchar() in C

Excellent... works great!
thanks for your help