File Locking

Back in Chapter 12, we instituted file locking for a guestbook CGI script using Perl’s sysopen function, and some fancy magic involving rewinding and truncating the guestbook file to write to it after obtaining an exclusive lock. The approach to file locking that we’ll be using in this case is different, in that it is based on the concept of a semaphore file. I first heard about semaphore files from Mark-Jason Dominus, one of the coolest Perl gurus around when it comes to explaining nifty Perl tricks in language even accidental programmers can understand.

The notion of a semaphore file sounded very familiar to me when I first heard about it, and after a few seconds I realized why: I had already been exposed to the concept back in kindergarten. All of us kids would sit in a circle, and when I wanted to say something I had to wait to be handed a special stuffed elephant that meant it was my turn to talk. Because there was only one stuffed elephant, there would (in theory) only be one child talking at any given time.

The semaphore file is the make_cf.plx script’s stuffed elephant. Only one copy of the script gets to hold it at a time, and only the copy holding it gets to read from and write to the CyberFair pages.

Here’s how it works. Up near the top of the make_cf.plx script (which was given as Example 15-1, back in Chapter 15), before any reading or writing has taken place, we add the following lines:

use Fcntl ':flock'; my $lock_file = '/my/private/dir/cyberfair.lock'; ...

Get Perl for Web Site Management now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.