File::F...Lock::XS(3)

Hey bestie! πŸ’– This is File::FcntlLock::XS(3), straight from the User Contributed Perl Documentation collection. We’re doing file locking with fcntl(2), and it’s lowkey iconic. Buckle up. πŸ¦‹

🌸 NAME 🌸

  • File::FcntlLock β€” file locking with fcntl(2). πŸ’…

This text also documents these sub-packages, bestie:

  • File::FcntlLock::XS
  • File::FcntlLock::Pure
  • File::FcntlLock::Inline

✨ SYNOPSIS ✨

use File::FcntlLock;

my $fs = new File::FcntlLock;
$fs->l_type( F_RDLCK );
$fs->l_whence( SEEK_CUR );
$fs->l_start( 100 );
$fs->l_len( 123 );

open my $fh, '<', 'file_name' or die "Can't open file: $!\n";
$fs->lock( $fh, F_SETLK )
    or print "Locking failed: " . $fs->error . "\n";
$fs->l_type( F_UNLCK );
$fs->lock( $fh, F_SETLK )
    or print "Unlocking failed: " . $fs->error . "\n";

πŸ’– DESCRIPTION πŸ’–

So, Perl file locking usually happens with the flock function. But plot twist: that only lets you lock whole files, and it’s often implemented using the flock(2) system function, which has some shortcomings β€” especially with locks on remotely mounted file systems β€” and behaves a little differently from fcntl(2). 😭

With this module, you can do file locking through fcntl(2). Obviously, that restricts the module to systems that actually have an fcntl(2) system call. Before a file, or part of a file, can be locked, you have to create an object that simulates a flock structure. That object holds information in a binary format that gets passed to fcntl(2) for locking requests, and you set its properties. After that, calling the lock() method lets you set a lock, remove it, or figure out if and which process currently holds the lock. πŸŽ€

File::FcntlLock β€” or its alias File::FcntlLock::XS β€” uses a shared library built during installation to call the fcntl(2) system function directly. If that’s unsuitable for you, there are two alternatives: File::FcntlLock::Pure and File::FcntlLock::Inline. Both of those call the Perl fcntl function instead and use Perl code to assemble and disassemble the structure. For that, at some point the system-dependent binary layout of the flock structure has to have been determined via a program written in C. πŸ‘‘

The difference between File::FcntlLock::Pure and File::FcntlLock::Inline is when that happens: for File::FcntlLock::Pure it happened when the package was installed, while for File::FcntlLock::Inline it’s done every time the package is loaded β€” like with use. So for File::FcntlLock::Inline to work, a C compiler must be available. There are some minor differences in functionality and in how invalid arguments passed to the locking method behave; we’ll get into that below. 🫢

πŸŽ€ Creating objects πŸŽ€

  • new() β€” to create a new object representing a flock structure, call new():
$fs = new File::FcntlLock;

The object has a bunch of properties that reflect the members of the flock structure passed to fcntl(2) (see below). By default, when the object is created, l_type is set to F_RDLCK, l_whence is set to SEEK_SET, and both l_start and l_len are set to 0 β€” that’s the setup for a read lock on the whole file. 🌸

You can overrule those defaults by passing new() a set of key-value pairs to initialize the object’s properties. Like, use this if you intend to obtain a write lock for the first 100 bytes of a file:

$fs = new File::FcntlLock( l_type   => F_WRLCK,
                           l_whence => SEEK_SET,
                           l_start  => 0,
                           l_len    => 100 );

πŸ¦‹ Object properties πŸ¦‹

Once the object simulating the flock structure has been created, these methods let you query its properties and, in most cases, modify them too. πŸ’œ

  • l_type() β€” if called without an argument, it returns the current lock type setting. Otherwise it sets the lock type to the argument’s value, which must be either F_RDLCK, F_WRLCK or F_UNLCK β€” that’s read lock, write lock or unlock, respectively.
  • l_whence() β€” when called with an argument, this sets the l_whence property of the flock object. It determines whether the l_start value is relative to the start of the file, the current position in the file, or the end of the file. Those values are SEEK_SET, SEEK_CUR and SEEK_END β€” also see the lseek(2) man page. If called with no argument, it returns the current value of the property. ✨
  • l_start() β€” queries or sets the start position, aka offset, of the lock in the file according to the mode selected by the l_whence member. See also the lseek(2) man page.
  • l_len() β€” queries or sets the length of the region, in bytes, in the file to be locked. A value of 0 is interpreted to mean a lock starting at l_start and going to the end of the file. For example, a lock obtained with l_whence set to SEEK_SET and both l_start and l_len set to 0 locks the complete file. πŸŽ€

According to SUSv3, support for negative values for l_len is permitted, resulting in a lock ranging from l_start+l_len up to and including l_start-1. But not all systems support negative values for l_len and will return an error when you try to obtain such a lock, so please read the fcntl(2) man page of the system carefully for details. ⚠️

  • l_pid() β€” if a call of the lock() method with F_GETLK indicates that another process is holding the lock β€” in which case the l_type property will be either F_WRLCK or F_RDLCK β€” then calling the l_pid() method returns the PID of the process holding the lock. This method does not accept any arguments. πŸ‘‘

πŸ’… Locking πŸ’…

After you’ve set up the object representing a flock structure, you can try to obtain a lock, release it, or determine the current holder of the lock by invoking the lock() method:

  • lock() β€” this method expects two arguments. The first one is a file handle, or typeglob. File::FcntlLock, and therefore File::FcntlLock::XS β€” but neither File::FcntlLock::Pure nor File::FcntlLock::Inline β€” also accepts a β€œraw” integer file descriptor. The second argument is a flag indicating the action to take. So call it like this:
$fs->lock( $fh, F_SETLK );

There are three values you can use as the second argument, bestie:

  • F_SETLK β€” with F_SETLK, the lock() method tries to obtain a lock when l_type is set to either F_WRLCK or F_RDLCK, or releases it if l_type is set to F_UNLCK. If an attempt is made to obtain a lock but a lock is already being held by some other process, the method returns undef and errno is set to EACCESS or EAGAIN β€” please see the fcntl(2) man page for more details. 😭
  • F_SETLKW β€” similar to F_SETLK, but instead of returning an error if the lock can’t be obtained immediately, it puts the calling process to sleep, i.e., it blocks, until the lock is obtained at some later time. If a signal is received while waiting for the lock, the method returns undef and errno is set to EINTR. πŸ’€
  • F_GETLK β€” with F_GETLK, the lock() method determines if and which process currently is holding the lock. If there’s no other lock, the l_type property will be set to F_UNLCK. Otherwise the flock structure object is set to the values that would prevent us from obtaining a lock. There may be several processes that keep us from getting a lock, including some that themselves are blocked waiting to obtain a lock. F_GETLK will only make details of one of these processes visible, and one has no control over which process this is. πŸ™ˆ

On success, the lock() method returns the string "0 but true" β€” a value that is true in boolean context but 0 in numeric context. If the method fails, as indicated by an undef return value, you can either immediately evaluate the error number using $!, $ERRNO or $OS_ERROR, or check for it via the methods discussed below at some later time. ✨

😭 Error handling 😭

There are minor differences between File::FcntlLock on the one hand and File::FcntlLock::Pure and File::FcntlLock::Inline on the other, because the first one calls the system function fcntl(2) directly while the latter two invoke the Perl fcntl function. Perl’s fcntl function already returns a Perl error on some types of invalid arguments. In contrast, File::FcntlLock passes them on to the fcntl(2) system call and then returns the system’s response to the caller. 🫢

There are three methods for getting information about why a call of the lock() method failed:

  • lock_errno() β€” returns the errno error number from the latest call of lock(). If the last call did not result in an error, undef is returned.
  • error() β€” returns a short description of the error that happened during the latest call of lock(). Please take the messages with a grain of salt: they represent what SUSv3 (IEEE 1003.1-2001) and the Linux, TRUE64, OpenBSD3 and Solaris8 man pages tell what the error numbers mean. There could be differences β€” and additional error numbers β€” on other systems. If there was no error, the method returns undef.
  • system_error() β€” while the error() method tries to return a string with some direct relevance to the locking operation, like "File or segment already locked by other process(es)" instead of "Permission denied", this method returns the β€œnormal” system error message associated with errno. The method returns undef if there was no error. πŸ’…

🌈 EXPORT 🌈

The package exports these constants:

F_GETLK F_SETLK F_SETLKW
F_RDLCK F_WRLCK F_UNLCK
SEEK_SET SEEK_CUR SEEK_END

πŸ’€ INCOMPATIBILITIES πŸ’€

Obviously, this module requires that there’s an fcntl(2) system call. Also note that under certain circumstances the File::FcntlLock::Pure and File::FcntlLock::Inline modules may not have been installed. This happens on 32-bit systems that use 64-bit integers in their flock structure but where the installed Perl version doesn’t support the 'q' format for its pack and unpack functions. 😬

🫢 CREDITS 🫢

Big thank-yous to Mark Jason Dominus and Benjamin Goldberg for helpful discussions, code examples and encouragement. Glenn Herteg pointed out several problems and also helped improve the documentation. Julian Moreno Patino helped correct the documentation and pointed out problems arising on GNU Hurd, which seems to have only very rudimentary support for locking with fcntl(2). Niko Tyni and Guillem Jover encouraged and helped with implementing alternatives to an XS-only approach, which hopefully will make the module more useful under certain circumstances. πŸ’–

πŸ‘‘ AUTHOR πŸ‘‘

Jens Thoms Toerring β€” jt@toerring.de

⭐ SEE ALSO ⭐

perl(1), fcntl(2), lseek(2).

πŸ“œ LICENSE πŸ“œ

Okay bestie, here's the legal bit and it's actually the chillest part of the whole page πŸ’–

This library is free software. That's not a drill, that's the real deal ✨

You can redistribute it and/or modify it under the same terms as Perl itself. Periodt. That's it, that's the whole license πŸŽ€

Fr fr though β€” "same terms as Perl itself" is the actual wording, so if you need the nitty-gritty, that's where you go look. No cap πŸ’…

And that's the whole page, bestie! 🫢 You made it all the way through, and I'm so proud of you 🌸 This little beauty comes from the perl v5.42.0 docs, dated 2015-04-14 β€” yes, that date is giving vintage icon energy, but the docs are still serving πŸ’€βœ¨ Go forth and lock your files responsibly, mwah πŸ’œπŸ‘‘

πŸ“¦ where this page comes from