open (FD, " < source.txt") or die "$!\n";
flock(FD, LOCK_EX);
print "Yeah i get the lock by pid=$$ at ", cur_time(), "\n";
sleep 10;
flock(FD, LOCK_UN);
print "Oops i lose the lock by pid=$$ at ", cur_time(), "\n";
close FD;
sub cur_time {
strftime "%H:%M:%S", localtime;
}
使用方法:
打开2个控制台(console),假设分别为A窗口和B窗口,在A命令行下输入:
perl flock.pl
此时会显示:
Yeah i get the lock by pid=6122 at 14:20:39
过2,3秒,在B控制台执行同样的命令:
perl flock.pl
则暂时无任何显示,等到A控制台的程序执行完毕,显示:
Oops i lose the lock by pid=6122 at 14:20:49
的时候,B控制台的程序立刻显示:
Yeah i get the lock by pid=6123 at 14:20:49
过10秒后程序结束并显示:
Oops i lose the lock by pid=6123 at 14:20:59
上述代码及演示说明了排他锁(LOCK_EX)是让多进程串行的对数据源进行操作。注意,这个演示里的source.txt必须是实现存在的!。
http://www.adp-gmbh.ch/perl/flock.html
flock calls are advisory. It won't affect any other script unless they use flock themselves as well. Here are five rules governing locks:
Locks don't affect anything except other locks. They don't stop anyone from opening, reading, writing, deleting, etc the file
There can only be one lock on an open file.
If someone holds a LOCK_EX lock, all attempts to get a lock will wait (LOCK_EX meaning exclusive lock) until the other process releases the lock.
If someone holds a LOCK_SH lock, all attempts to get a LOCK_EX will fail, while other processes can aquire another LOCK_SH lock (LOCK_SH standing for shared lock)
The call to flock will not return until the lock can be aquired unless the lock is tried with LOCK_SH | LOCK_NB in which case the flock call will fail if another process has already aquired the lock.
建议使用flock. 这不会影响其他任何不使用flock的Script. 下面是掌握locks的五个规则:
1, Locks只会影响其他locks. 不会阻止进程打开,读,写,删除文件等操作。
2, 每个打开的文件只能有一个lock.
3, 如果一个进程有LOCK_EX (独占)lock,则其他进程只能等待知道该进程释放后取得。(补充:包括请求LOCK_EX和LOCK_SH lock)
4, 如果一个进程有LOCK_SH (共享)lock,则任何试图取得LOCK_EX的进程将失败,但是可以同时取得LOCK_SH lock;
5, 对flock请求直到获得之后才会返回,除非lock是用 LOCK_SH| LOCK_NB(非封锁 non-block)取得的,这时一旦其他进程已经有lock,将直接返回错误信息。
注:最后一点翻译可能有误,不太明白。实验结果:
如果是同时读两个文件并都使用flock函数,如果从前一个进程的LOCK_EX lock申请LOCK_EX lock,或者如果前一个进程是LOCK_SH lock,申请LOCK_EX lock都需要等待第一个进程结束。如果第一个进程是LOCK_SH lock,第二个进程申请LOCK_SH lock可以马上得到。