Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 14.3 RecordLocking 489


Example — Requesting and Releasing a Lock


To save ourselves from having to allocate anflockstructureand fill in all the elements
each time, the functionlock_regin Figure14.5 handles all these details.
#include "apue.h"
#include <fcntl.h>
int
lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type; /* F_RDLCK, F_WRLCK, F_UNLCK */
lock.l_start = offset; /* byte offset, relative to l_whence */
lock.l_whence = whence; /* SEEK_SET, SEEK_CUR, SEEK_END */
lock.l_len = len; /* #bytes (0 means to EOF) */
return(fcntl(fd, cmd, &lock));
}

Figure 14.5 Function to lock or unlock a region of a file

Since most locking calls are to lock or unlock a region (the commandF_GETLKis rarely
used), we normally use one of the following five macros, which aredefined inapue.h
(Appendix B).

#define read_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLK, F_RDLCK, (offset), (whence), (len))
#define readw_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLKW, F_RDLCK, (offset), (whence), (len))
#define write_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLK, F_WRLCK, (offset), (whence), (len))
#define writew_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLKW, F_WRLCK, (offset), (whence), (len))
#define un_lock(fd, offset, whence, len) \
lock_reg((fd), F_SETLK, F_UNLCK, (offset), (whence), (len))

We have purposely defined the first three arguments to these macros in the same order
as thelseekfunction.

Example — Testing for a Lock


Figure14.6 defines the functionlock_testthat we’ll use to test for a lock.
#include "apue.h"
#include <fcntl.h>
pid_t
lock_test(int fd, int type, off_t offset, int whence, off_t len)
{
Free download pdf