Perl显示长函数的更新

时间:2015-06-25 17:04:43

标签: perl

我有一个运行SQL查询的Perl脚本,需要一段时间才能获取信息。有没有办法显示某种更新,让用户知道该程序仍在运行?我想在每隔几秒钟打印.,直到查询完成。

不幸的是,我不确定如何一次运行2个函数(一个用于查询,另一个用于打印...

1 个答案:

答案 0 :(得分:2)

#!/usr/bin/env perl                                                                         

use warnings;
use strict;
use POSIX qw( :sys_wait_h );

$|++; # See print and print messages in correct order                                       
main();
1;

sub main {
    print "About to Fork\n";

    if (my $pid = fork()) {
        # parent                                                                            
        print "PARENT: Waiting for child\n";
        sleep 1;
        while(waitpid(-1, WNOHANG) > -1) {
            print '.';
            sleep 1;
        }
        print "\n";
        print "PARENT: Child finished\n";
        print "PARENT: Exiting...\n";
    } else {
        # child                                                                             
        print "CHILD: Starting\n";
        run_sql();
        print "\nCHILD: Exiting\n";
        exit 0;
    }
}

sub run_sql {
    # put your sql code here                                                                
    sleep 10;
}

This will output:

About to Fork
PARENT: Waiting for child
CHILD: Starting
.........
CHILD: Exiting
.
PARENT: Child finished
PARENT: Exiting...