[ Perl ] 如何限制某段程序的运行时间

https://www.cnblogs.com/yeungchie/

关键函数

alarm

alarm.pl

#!/usr/bin/env perl
use v5.10;
use warnings;
use strict;
use POSIX qw(strftime);

say "start - ".(strftime '%Y-%m-%d %H:%M:%S',localtime);

my $timeout = 3;
eval {
    local $SIG{ALRM} = sub{
        say "timeout - ".(strftime '%Y-%m-%d %H:%M:%S',localtime);
        die;
    };
    alarm $timeout;
    my $count = 1;
    while(1){
        say $count++;
        sleep 1;
    }
};

say "done - ".(strftime '%Y-%m-%d %H:%M:%S',localtime);

run

> ./alarm.pl
start - 2021-08-06 01:08:35
1
2
3
timeout - 2021-08-06 01:08:38
done - 2021-08-06 01:08:38
posted @ 2021-08-06 01:09  YEUNGCHIE  阅读(347)  评论(0编辑  收藏  举报