我有一个Perl模块,我的收集脚本库使用它。这些脚本用于扫描我的网络,在我的网络设备上执行各种任务等。
大约有15个用户
,我只希望每次只有1个
人运行收集脚本。如果第二个用户尝试运行脚本,则希望他们等待第一个人完成。
下面的代码仅是测试平台,以便在投入生产之前正确运行它。我有一个具有nap
函数的模块。我只希望一次只有一个人打盹。
sub nap {
my $program = shift;
my @arr;
#open file to check the queue
open(IN, $path); @arr=<IN>; close IN;
#if someone is in the queue, print it out!
$|++;
if (@arr > 0) { print @arr; }
#keep checking the queue, once the queue is empty it's my turn!
while (@arr != 0) {
open(IN, $path); @arr=<IN>; close IN;
sleep 1;
}
#it's my turn, put my name in the queue
open(IN,">",$path);
print IN "$ENV{USER},$program";
close IN;
#take a nap!
print "\n Sleep starting \n";
sleep 10;
#I'm finished with my nap, clear the queue so other's can go
open(IN,">",$path);
close IN;
print "\nsleep over\n";
}
我的问题是,如果只有
1个用户
在等待,那么它可以正常工作,但是如果有2个用户
在等待,他们仍然会同时休眠(在第一个用户完成后)。我能否锁定或阻止此文件?我已经看到了
flock
,但无论如何锁定它,用户仍然可以读取。这是否是正确的解决方案?还是有更好的用于这些目的的方法?