File locking is a mechanism that lets processes (that is, running programs) safely share reading and writing access to files without violating their integrity. A locked file tells the operating system that it is currently in use.
Locks are a necessary precaution in a CGI environment. A web server 'copies' itself to allow multiple simultaneous connections. It is therefore possible that more than one connection accesses a CGI script and any associated file at the same time. If more than one process would try to write to the file, the file's content would be corrupted. File locks make sure that only one process at a time gets access.
There are two different kinds of locks: shared and exclusive. A shared lock allows multiple read access, that is, it notifies other processes that the file is currently being read. An exclusive lock is applied when a process wants to write to a file. It will notify the operating system to bar other processes from access while the lock is active.
Locks are applied with the flock( )
function. This function takes two parameters: a file handle and an integer that represents the lock operation.
1 | shared lock |
2 | exclusive lock |
8 | unlock |
The following script illustrates how an exclusive lock is applied.
$file = "file.txt"; open(FILE, "$file") || die; flock(FILE, 2); # apply lock while(<FILE>) { # ... write to file } flock(FILE, 8); # release lock close(FILE);
Explicitly unlocking a file is not necessary as long as the file is closed.
Since locks bar access to a file, the active time period of a lock should be as short as possible. Time consuming computing operations should not be applied while a lock is active.
flock( )
is a Unix functions. If a file-locking Perl script runs under another operating system that does not have this function, the script will cause a terminal error.
File locking only works with scripts that actually implement locks. There is nothing that prevents processes to read or write to a locked file if they don't try to lock a file themselves.