Perl 子程序超时

Perl subroutine timeout

我有一个子程序通常需要 1 秒才能完成 运行。有时,它可以 运行 无限。如果子例程花费的时间太长(> 10 秒),我想继续编写代码并忽略该子例程的 运行。这是我到目前为止使用警报的结果。

use Win32::OLE;

eval { 
    local $SIG{ALRM} = sub { die "alarm\n" };
    alarm 10;                   # schedule alarm in 10 seconds 
    &do_the_subroutine;
    alarm 0;                    # cancel the alarm
};

if ($@) {
    $error_string .= $script;
    #Do something else if the subroutine took too long.
}

do_the_subroutine{
# use existing instance if Excel is already running
    eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
    die "Excel not installed" if $@;
    unless (defined $ex) {
        $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
                or die "Oops, cannot start Excel";
    }

    # get a new workbook
    $book = $ex->Workbooks->Add;

    # write to a particular cell
    $sheet = $book->Worksheets(1);
    $sheet->Cells(1,1)->{Value} = "foo";

    # write a 2 rows by 3 columns range
    $sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ],
                                       [ 42,    'Perl',  3.1415  ]];

    # print "XyzzyPerl"
    $array = $sheet->Range("A8:C9")->{Value};
    for (@$array) {
        for (@$_) {
            print defined($_) ? "$_|" : "<undef>|";
        }
        print "\n";
    }

    # save and exit
    $book->SaveAs( 'test.xls' );
    undef $book;
    undef $ex;
}

&do_the_subroutine 从来没有 returns 所以我无法继续前进。我也无法将此代码块放入该子例程中。有什么想法吗?

我怀疑 alarm 在 Windows 上根本无法实现您想做的事情。

来自perldoc perlport

alarm Emulated using timers that must be explicitly polled whenever Perl wants to dispatch "safe signals" and therefore cannot interrupt blocking system calls. (Win32)