Open In App

Perl | File Locking

File locking, or locking in general, is just one of the various solutions proposed to deal with problems associated with resource sharing.
File locking is a method to preserving the security and integrity of any document. The main motive of file locking is allowing people to commit changes to the document without creating a mess of it. When a file is trying to be changed by two or more users, there could be conflicts that arise.

For example, let us consider a file containing the data of a project. The whole project team is allowed to modify the file. There will be a CGI script coded on the web to do the following.






$file = "project.docx";
$commit = $ENV{'QUERY_INFO'};
open(FILE, "$file"); #opening the document
while() {
  if (m/^$commit$/) {
    print "Change already made\n";
    exit;
  }
}
close(FILE);
push(@newcommit, $commit);
open(FILE, ">$file");
print ...
close(FILE);
print "Commit made!";
exit;

Locking of a file is done at the system level, which means that the actual details of applying the lock is not something a user has to worry about. File locks are introduced to set temporary restrictions on certain files to limit how they can be shared among different processes. Depending on the nature of an operation, we come up with two types of locks. The first type is a shared lock, and another one is an exclusive lock. With respect to files, read access can be shared by multiple processes because read access does not result in any changes to the state of the shared resource. Therefore, a consistent view of the shared resource can be maintained.
File locking can be done, in Perl, with the flock command.

flock()

flock() accepts two parameters. The first one is the filehandle. The second argument indicates the locking operation required.

Syntax:

flock [FILEHANDLE], [OPERATION]

Here, OPERATION is a numeric value, it can be either 1, 2, 4, or 8.
These numeric values have different meaning and are used to perform different operations such as:

Perl uses numbers to represent the values:

sub LOCK_SH { 1 } ## set as shared lock
sub LOCK_EX { 2 } ## set as exclusive lock
sub LOCK_NB { 4 } ## set lock without any blocks
sub LOCK_UN { 8 } ## unlock the FILEHANDLE

Article Tags :