One, Scene
In addition to process synchronization between multiple semaphores, shared memory (atomic) sync, but also may be used to implement file locks.
Second, the realization
There are two ways are linux, namely flock () function and the fcntl () function. Using substantially the same effect
flock function:
fd: file descriptor
operation: LOCK_SH (add a shared lock, the equivalent of a read lock ), LOCK_EX (add exclusive lock, equivalent to a write lock ), LOCK_UN (added to remove the lock file, unlock ),
LOCK_NB (which can be used in combination LOCK_SH and LOCK_EX default alone LOCK_SH and LOCK_EX in the case did not get a lock resource, will be blocked, then add LOCK_NB, naturally it is not blocked , the direct return results)
fcntl function:
Use file locks are:
int fcntl(int fd, int cmd, struct flock *);
struct flock definitions:
fd: file descriptor
cmd: F_GETLK (file locks access to information, query ), F_SETLK (setting information file lock, lock, unlock, default is not blocked ), F_SETLKW (setting information file lock, lock, unlock, default blocking )
struct flock l_type: F_RDLCK ( read lock ), F_WRLCK ( write lock ), F_UNLCK ( unlocked )
struct flock l_whence: file locking specific location, use the time to set the same location can achieve the effect of lock, SEEK_SET (beginning of the file), SEEK_CUR (files in the current location), SEEK_END (End of File)