LOCK_EX是表示排它鎖(Exclude),是獨佔的,通常用於寫操做,而若是換成LOCK_SH(Share)則是共享,多用於讀取。有時爲了保證多進程對文件的讀寫都是惟一的,不管讀寫都進行LOCK_EX的請求。 spa
如下是一段演示程序,名叫flock.pl use Fcntl qw(:flock); use POSIX qw(strftime); 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; }