Program: lockarea
Perl’s flock
function only locks complete files, not regions of the file. Although
fcntl
supports locking of a file’s regions,
this is difficult to access from Perl, largely because no one has
written an XS module that portably packs up the necessary structure.
The program in Example 7.11 implements
fcntl
, but only for the three architectures it
already knows about: SunOS, BSD, and Linux. If you’re running
something else, you’ll have to figure out the layout of the
flock
structure. We did this by eyeballing the
C-language sys/fcntl.h
#include
file—and running the
c2ph program to figure out alignment and typing.
This program, while included with Perl, only works on systems with a
strong Berkeley heritage, like those listed above. As with Unix
—or Perl itself—you don’t
have to use c2ph, but it
sure makes life easier if you can.
The
struct_flock
function in the
lockarea program packs and unpacks in the proper
format for the current architectures by consulting the
$^O
variable, which contains your current
operating system name. There is no struct_flock
function declaration. It’s just aliased to the
architecture-specific version. Function aliasing is discussed in
Section 10.14.
The lockarea program opens a temporary file, clobbering any existing contents and writing a screenful (80 by 23) of blanks. Each line is the same length.
The program then forks one or more times and lets all the child processes try to update the file at the same time. The first argument, N
Get Perl Cookbook 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.