File Locking
In a multitasking environment, you need to be careful not to collide with other processes that are trying to use the same file you’re using. As long as all processes are just reading, there’s no problem; however, as soon as even one process needs to write to the file, complete chaos ensues unless some sort of locking mechanism acts as traffic cop.
Never use the mere existence of a filename (that is, –e $file) as a locking indication, because a
race condition exists between the test for existence of that filename
and whatever you plan to do with it (like create it, open it, or unlink
it). See the section Handling Race Conditions in Chapter 20 for more about this.
Perl’s portable locking interface is the flock(HANDLE,FLAGS)
function, described in Chapter 27. Perl maximizes
portability by using only the simplest and most widespread locking
features found on the broadest range of platforms. These semantics are
simple enough that they can be emulated on most systems, including those
that don’t support the traditional syscall of that name, such as System
V or Windows NT. (If you’re running a Microsoft system earlier than NT,
though, you’re probably out of luck, as you would be if you’re running a
system from Apple before Mac OS X.)
Locks come in two varieties: shared (the LOCK_SH flag) and
exclusive (the LOCK_EX flag).
Despite the suggestive sound of “exclusive”, processes aren’t required
to obey locks on files. That is, flock only implements advisory locking, which means that ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access