Free Perl Tutorials

Using the flock() function in PERL

WHAT IS THE FLOCK() FUNCTION IN PERL?
The flock() or file lock function prevents multiple users from opening and editing pieces of data in a single file. Ultimately, it prevents loss of data. Say for instance you have one user who opens a file to append it, and add a line, another user comes along and opens the file before the person appending the file updates it. The user who came in 2nd will open the file unprotected by the flock function. Then the 1st user will update the file. The 2nd user did not get the update, and then updates the original file with their information. When they update the file, the changes created by the 1st user will be written over, creating a problem.

flock solves that problem for us in perl by only allowing 1 user at a time to open, edit, and append files in perl.

HOW TO USE THE FLOCK() FUNCTION IN PERL
We'll use the code example from our other tutorial, How to open a file in PERL

open (FILE, ">>hey.txt"
flock(FILE,2);
print FILE "This is line 1\n";
print FILE "This is line 2\n";
close (FILE);


I have put in bold the coding. It is very simple to lock a file. Here is the explanation fo the flock function:


flock(FILE HANDLE, 2 means that only 1 user at a time can append the file);

So it looks like this:

flock(FILE,2);


Using flock to lock a file you are appending is good practice!