Apply or remove an advisory lock on an open file
#include <fcntl.h> int flock( int filedes, int operation );
- The file descriptor of an open file.
- What you want to do to the file; see below.
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The flock() function applies or removes an advisory lock on the file associated with the open file descriptor filedes. To establish a lock with this function, open with write-only permission (O_WRONLY ) or with read/write permission (O_RDWR ).
A lock is applied by specifying one of the following values for operation:
- Exclusive lock.
- Don't block when locking. This may be ORed with LOCK_EX or LOCK_SH to give nonblocking behavior.
- Shared lock.
- Unlock an existing lock operation.
Advisory locks allow cooperating processes to perform consistent operations on files, but they don't guarantee consistency.
The locking mechanism allows two types of locks: shared and exclusive. At any time, multiple shared locks may be applied to a file, but at no time are multiple exclusive, or both shared and exclusive, locks allowed simultaneously on a file.
A shared lock may be upgraded to an exclusive lock, and vice versa, by specifying the appropriate lock type. The previous lock is released and a new lock is applied (possibly after other processes have gained and released the lock).
Requesting a lock on an object that's already locked causes the caller to be blocked until the lock may be acquired. If you don't want the caller to be blocked, you can specify LOCK_NB in the operation to fail the call (errno is set to EWOULDBLOCK).
Processes blocked awaiting a lock may be awakened by signals.
- The operation was successful.
- An error occurred (errno is set).
- Invalid descriptor, filedes.
- The argument operation doesn't include one of LOCK_EX , LOCK_SH , or LOCK_UN .
- The system can't allocate sufficient memory to store lock resources.
- The filesystem doesn't support the operation.
- The filedes argument refers to an object other than a file.
- The file is locked and LOCK_NB was specified.