如何在perl中专门读取文件?
我有一个perl模块,我的收集脚本库使用.这些脚本用于扫描我的网络,在我的网络设备上执行各种任务等.
大约有15个用户,我一次只想要一个人来运行收集脚本.如果第二个用户尝试运行脚本,那么我希望他们等到第一个人完成. 下面的代码只是一个测试床,所以我可以让它在投入生产之前正常工作.我有一个具有午睡功能的模块.我只希望一个人一次打盹. 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 overn"; } 我的问题是,如果1个用户正在等待它是有效的,但如果2个用户正在等待,他们仍然同时小睡(在第一个用户完成后) 我可以锁定或阻止此文件吗?我见过flock但看起来无论你如何锁定它,用户仍然可以阅读. 这是一个正确的解决方案吗?还是有更好的东西用于这些目的? 解决方法
您可以锁定文件的DATA部分以锁定文件本身,因此您可以(ab)使用它来控制对该脚本的独占访问.
我把它放在一个库文件nap.pl中: #!usr/bin/env perl use strict; use Fcntl qw(LOCK_EX LOCK_NB); sub nap { ## make sure this script only runs one copy of itself until ( flock DATA,LOCK_EX | LOCK_NB) { print "someone else has a lockn"; sleep 5; } } __DATA__ This exists to allow the locking code at the beginning of the file to work. DO NOT REMOVE THESE LINES! 然后我打开了3个终端并在每个终端中运行: #!/usr/bin/env perl use strict; do 'nap.pl'; ≉ print `ls /tmp/`; sleep 5; 第一个终端立即打印了我的/ tmp目录的内容. 但要注意将它放在库中的位置,你要确保没有锁定不相关的子程序. 我个人会把锁码放在每个收集脚本中,而不是放在库中.收集脚本是你实际上只想运行一个实例的.看起来你的标题不准确:你不是试图专门读取文件,而是试图专门运行文件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |