perl function flock
The flock
function in Perl is used to apply advisory locks on files. It takes two arguments: the filehandle to lock and the type of lock to apply. The lock type can be either shared (LOCK_SH
) or exclusive (LOCK_EX
).
Here's an example of using flock
to apply an exclusive lock on a file:
open(my $fh, '>>', 'filename.txt') or die "Can't open file: $!"; flock($fh, LOCK_EX) or die "Can't lock file: $!"; # write to the file print $fh "Some text to write to the file.\n"; # release the lock flock($fh, LOCK_UN); close $fh;Source:www.theitroad.com
In this example, the open
function is used to open the file filename.txt
in append mode. The flock
function is then called with the filehandle $fh
and the lock type LOCK_EX
to apply an exclusive lock on the file. The print
function is then used to write some text to the file while the lock is held. Finally, the flock
function is called again with the filehandle $fh
and the lock type LOCK_UN
to release the lock, and the close
function is used to close the filehandle.
Note that flock
applies advisory locks, which means that it is up to the cooperating processes to respect the locks. If another process attempts to access the locked file without checking the lock first, it can still modify the file.