FileLocker.h
Classes
- FileLocker -- Class to handle file locking. (full description)
Types
- Read
-
Acquire a read lock.
- Write
-
Acquire a write lock.
Interface
- Public Members
- FileLocker()
- explicit FileLocker (int fd, uInt start=0, uInt length=0)
- ~FileLocker()
- Bool acquire (LockType = Write, uInt nattempts = 0)
- Bool release()
- Bool canLock (LockType = Write)
- Bool canLock (uInt& pid, LockType = Write)
- Bool hasLock (LockType = Write) const
- int fd() const
- int lastError() const
- String lastMessage() const
Review Status
- Reviewed By:
- UNKNOWN
- Date Reviewed:
- before2004/08/25
- Programs:
- Tests:
Prerequisite
Synopsis
This class handles file locking by means of the fcntl SETLK function.
Locking of files on NFS-mounted file systems works correctly
as long as the NFS lockd and statd deamons are configured correctly.
Otherwise lock requests may be granted incorrectly.
Acquiring a lock can be done for a read or a write lock.
Multiple locks on a file can exist as long as they are all
read locks. When a write lock is involved, no other lock can exist.
It is possible to acquire a lock in 2 ways:
- Wait until the lock request is granted; i.e. until the processes
holding a lock on the file release their lock.
- Do several attempts; between each attempt it sleeps 1 second.
Note that nattempts=1 means it returns immediately when the
lock request could not be granted.
Example
int fd = open ("file.name");
FileLocker lock(fd);
if (lock.acquire()) {
... do something with the file ...
lock.release();
}else{
cout << lock.lastMessage() << endl;
}
Motivation
Make it possible to lock files in a standard way.
Member Description
Define the possible lock types.
Default constructor creates an invalid fd.
explicit FileLocker (int fd, uInt start=0, uInt length=0)
Construct the FileLocker object for the given file descriptor.
This can be used to lock a segment of the given file.
The segment is given by start and length. Length=0 means till the
end of the file.
Bool acquire (LockType = Write, uInt nattempts = 0)
Acquire a write or read lock.
nattempts defines how often it tries to acquire the lock.
A zero value indicates an infinite number of times (i.e. wait until
the lock is acquired).
A positive value means it waits 1 second between each attempt.
Release a lock.
The return status indicates if an error occurred.
Test if the file can be locked for read or write.
Optionally the PID of the process holding the lock is returned.
Test if the process has a lock for read or write on the file.
int fd() const
Get the fd in use.
Get the last error.
Get the message belonging to the last error.