- 论坛徽章:
- 0
|
- #Timeout read
- #This is a timeout read subroutine which implement windows and UNIX system differently based on $^O
- ##Please remember to add "use Config" at the top of your program
- ##my $res = time_out("timeout")
- ##The timeout is specify with "timeout" value, default to 3s, you can change it at your will
- ##If user input something within the specified time, the input is stored in $res
- ##else timedout, and a default value "No input" is returned, you can change the default value in the code
- sub timeout_read {
- my $timeout = 5; #Default to 5 s
- $timeout = shift if @_;
- my $tmpfile = "tmp"; #The name of the temporary created file
- my $result = "No input"
- ; #The default return value, you can change it to anything you want
- #Depending on the operating system, treat the timeout problem accordingly
- if ( $^O =~ /MSWin32/i ) {
- #This is windows OS, so we could use Win32::Job to implement it
- eval "use Win32::Job";
- my $job = Win32::Job->new;
- #Create a job to read the user input and redirect the stdout to a file called tmp
- $job->spawn(
- $Config{perlpath},
- q{perl -e "print scalar <STDIN>"},
- { stdout => "tmp" },
- );
- my $status = $job->run($timeout);
- if ($status) { #User has input something
- chomp( $result = qx /type $tmpfile/ );
- unlink $tmpfile or warn "Fail to remove $tmpfile";
- }
- }
- else {
- #This is a UNIX like system, so could implement the timeout read in alarm call
- my $tmp;
- eval {
- local $SIG{ALRM} = sub { die "alarm\n" };
- alarm $timeout;
- chomp( $tmp = <STDIN> );
- };
- if ($@) {
- die $@ if $@ ne "alarm\n";
- }
- else {
- $result = $tmp;
- }
- }
- #Finally, reset the alarm
- alarm 0;
- return $result;
- }
复制代码
这是我以前写的一个超时阅读函数,在Linux和windows上都可以用
通过my $res = time_out("$timeout");调用
默认的超时时间是5s,如果没有输入,返回"No input",反之则返回用户输入的数据,你可以自己根据实际的应用情况照着修改,反正源代码都贴了 |
|