QNX Developer Support
![]() |
![]() |
![]() |
![]() |
flock()
Apply or remove an advisory lock on an open file
Synopsis:
#include <fcntl.h>
int flock( int filedes,
int operation );
Arguments:
- filedes
- The file descriptor of an open file.
- operation
- What you want to do to the file; see below.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
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:
- LOCK_EX
- Exclusive lock.
- LOCK_NB
- Don't block when locking. This may be ORed with LOCK_EX or LOCK_SH to give nonblocking behavior.
- LOCK_SH
- Shared lock.
- LOCK_UN
- 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).
![]() |
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.
Returns:
- 0
- The operation was successful.
- -1
- An error occurred (errno is set).
Errors:
- EBADF
- Invalid descriptor, filedes.
- EINVAL
- The argument operation doesn't include one of LOCK_EX, LOCK_SH, or LOCK_UN.
- ENOMEM
- The system can't allocate sufficient memory to store lock resources.
- EOPNOTSUPP
- The filedes argument refers to an object other than a file.
- EWOULDBLOCK
- The file is locked and LOCK_NB was specified.
Classification:
| Safety: | |
|---|---|
| Cancellation point | No |
| Interrupt handler | No |
| Signal handler | Yes |
| Thread | Yes |
See also:
![]() |
![]() |
![]() |
![]() |

![[Previous]](../prev.gif)
![[Contents]](../contents.gif)
![[Index]](../keyword_index.gif)
![[Next]](../next.gif)

