1134 Chapter 55
z The regionIsLocked() function tests whether a lock can be placed on a file. The
arguments of this function are as for lockRegion(). This function returns 0
(false) if no process holds a lock that conflicts with the lock specified in the call.
If one of more processes hold conflicting locks, then this function returns a
nonzero value (i.e., true)—the process ID of one the processes holding a con-
flicting lock.
Listing 55-3: File region locking functions
––––––––––––––––––––––––––––––––––––––––––––– filelock/region_locking.c
#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;