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; one of the following:
- LOCK_EX—apply an exclusive lock.
- LOCK_SH—apply a shared lock.
- LOCK_UN—unlock an existing lock.
You can OR LOCK_NB with LOCK_EX or LOCK_SH to prevent the function from blocking (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.
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 make the call fail instead (errno is set to EWOULDBLOCK).
Locks are applied to files, not file descriptors. That is, file descriptors duplicated through dup() or fork() don't result in multiple instances of a lock, but rather multiple references to a single lock. If a process holding a lock on a file forks, and the child explicitly unlocks the file, the parent loses its lock.
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 already locked, and LOCK_NB was specified.
Last modified: 2013-12-23