filelock/region_locking.c

This is filelock/region_locking.c (Listing 55-3, page 1134), an example from the book, The Linux Programming Interface.

The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

This page shows the "distribution" or "book" version of the file (why are there two versions?), or the differences between the two versions. You can switch between the views using the tabs below.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.

  Cover of The Linux Programming Interface
+/* region_locking.c
+
+   Some useful functions for file region (fcntl()) locking.
+*/
 #include <fcntl.h>
 #include "region_locking.h"             /* Declares functions defined here */
 
 /* Lock a file region (private; public interfaces below) */
 
 static int
 lockReg(int fd, int cmd, int type, int whence, int start, off_t len)
 {
     struct flock fl;
 
     fl.l_type = type;
     fl.l_whence = whence;
     fl.l_start = start;
     fl.l_len = len;
 
     return fcntl(fd, cmd, &fl);
 }
 
 int                     /* Lock a file region using nonblocking F_SETLK */
 lockRegion(int fd, int type, int whence, int start, int len)
 {
     return lockReg(fd, F_SETLK, type, whence, start, len);
 }
 
 int                     /* Lock a file region using blocking F_SETLKW */
 lockRegionWait(int fd, int type, int whence, int start, int len)
 {
     return lockReg(fd, F_SETLKW, type, whence, start, len);
 }
 
 /* Test if a file region is lockable. Return 0 if lockable, or
    PID of process holding incompatible lock, or -1 on error. */
 
 pid_t
 regionIsLocked(int fd, int type, int whence, int start, int len)
 {
     struct flock fl;
 
     fl.l_type = type;
     fl.l_whence = whence;
     fl.l_start = start;
     fl.l_len = len;
 
     if (fcntl(fd, F_GETLK, &fl) == -1)
         return -1;
 
     return (fl.l_type == F_UNLCK) ? 0 : fl.l_pid;
 }

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1