如何限制在Perl脚本的特定部分中花费的时间?

有没有办法建立一个时间计数器,使脚本的部分运行只要它滴答?例如,我有以下代码
for my $i (0 .. $QUOTA-1) {
    build_dyna_file($i);
    comp_simu_exe;
    bin2txt2errormap($i);
}

从理论上讲,我想运行这个循环3分钟,即使循环指令尚未完成,它仍然应该在3分钟后突破循环.

实际上,程序打开一个时间计数器窗口,它与脚本的一部分并行工作(每次调用它).

此外,子调用’comp_simu_exe’运行外部模拟器(在shell中),当超时结束时 – 此过程也必须被杀死(不要假设在一段时间后返回).

sub comp_simu_exe{

system("simulator --shell");
}

系统函数调用之间是否有任何关联?

解决方法

这是第二个答案,它涉及超时第二个过程的情况.使用这种情况启动外部程序并确保它不会花太长时间:
my $timeout = 180;
my $pid = fork;

if ( defined $pid ) {
    if ( $pid ) {
        # this is the parent process
        local $SIG{ALRM} = sub { die "TIMEOUT" };
        alarm 180;
        # wait until child returns or timeout occurs
        eval {
            waitpid( $pid,0 );
        };
        alarm 0;

        if ( $@ && $@ =~ m/TIMEOUT/ ) {
            # timeout,kill the child process
            kill 9,$pid;
        }
    }
    else {
        # this is the child process
        # this call will never return. Note the use of exec instead of system
        exec "simulator --shell";
    }
}
else {
    die "Could not fork.";
}

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...