File Locking

Now that we’ve got our guestbook entry looking how we want it, we need to combine it with the earlier entries and save the whole kit and caboodle in a file on the server.

Which raises an interesting issue. Depending on how popular our site is, it’s entirely possible that two people will try to view the guestbook—or worse, add new entries to it—at the same time. This could create a problem, causing us to end up with some really weird-looking guestbook entries.

We get around this problem by using something called file locking. This is a way of marking a file as “ours,” at least temporarily. Assuming the other programs that want to access our file are written to respect file locking, they will wait patiently for us to finish what we’re doing before they do whatever it is they want to do.

This is a pretty simple concept; anyone who has ever needed to keep two preschoolers happily playing with the same toy will understand the principle. That said, the actual implementation tends to be a bit more complicated than one might at first expect (which is also true for preschoolers, come to think of it).

There are two basic approaches to file locking. One way would be to use something called a semaphore file , which is a separate file, other than our data file, where we would do our actual locking. We use that technique for several file locking examples later in this book. For this example, though, we’re going to do our file locking using the actual guestbook data file itself. ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.