【发布时间】:2014-02-03 14:52:17
【问题描述】:
我需要将外部进程(命令行调用)的执行包含在固定的时间窗口中。
经过几次阅读后,我编写了这个实现:
#/bin/perl -w
use IPC::System::Simple qw( capture );
use strict;
use threads;
use threads::shared;
use warnings;
my $timeout = 4;
share($timeout);
my $stdout;
share($stdout);
my $can_proceed = 1;
share($can_proceed);
sub watchdogFork {
my $time1 = time;
my $ml = async {
my $sleepTime = 2;
my $thr = threads->self();
$stdout = capture("sleep $sleepTime; echo \"Good morning\n\";");
print "From ml: " . $stdout;
$thr->detach();
};
my $time2;
do {
$time2 = time - $time1;
} while ( $time2 < $timeout );
print "\n";
if ( $ml->is_running() ) {
print "From watchdog: timeout!\n";
$can_proceed = 0;
$ml->detach();
}
}
my $wd = threads->create('watchdogFork');
$wd->join();
print "From main: " . $stdout if ($can_proceed);
当$timeout > $sleepTime 返回时:
From ml: Good morning
From main: Good morning
另一方面,当$timeout < $sleepTime:
From watchdog: timeout!
获得的行为是正确的,但我认为这种方法有点原始。
我想知道是否有库可以帮助改进源代码以提高可读性和性能。有什么建议吗?
【问题讨论】:
标签: multithreading perl shell process watchdog