sub LockFile { local $path = $_[0] ; local $mode = $_[1] ; local $flockPath = $path . '.lck' ; local $flockFH = $flockPath ; open ($flockFH, ">$flockPath") or die ("Failed to open $flockPath") ; if (flock ($flockFH, $mode)) { use Fcntl ; local $fexistPath = $path . '.lck.tmp' ; if ($mode & LOCK_EX) { local $fexistFH = $fexistPath ; sysopen ($fexistFH, $fexistPath, O_WRONLY | O_CREAT | O_EXCL) or die ("Acquired an exclusive lock for $flockPath but cannot create $fexistPath.") ; close $fexistFH ; } elsif (-e $fexistPath) { die ("Acquired a shared lock for $flockPath but found that $fexistPath exists.") ; } } else { die ("System Busy") ; } return ($flockFH, $path, $mode) ; } sub UnlockFile { use Fcntl ; local $fh = $_[0] ; local $path = $_[1] ; local $mode = $_[2] ; if ($mode & LOCK_EX) { local $fexistPath = $path . '.lck.tmp' ; unlink ($fexistPath) > 0 or die ("Failed to delete the lock file $fexistPath.") ; } close ($fh) ; } #### local ($lockFH, $lockPath, $lockMode) = LockFile ("test.txt", 2); # Wait 10 seconds before calling UnlockFile UnlockFile ($lockFH, $lockPath, $lockMode);