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
file. I first heard about semaphore files from Mark-Jason
one of the coolest Perl gurus around when it comes to explaining
nifty Perl tricks in language even accidental programmers can
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
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.
use Fcntl ':flock'; my $lock_file = '/my/private/dir/cyberfair.lock'; ...