delorie.com/djgpp/doc/libc/libc_329.html   search  
libc.a reference

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

flock

Syntax

 
#include <sys/file.h>

int flock (int _fildes, int _op);

Description

Apply or remove an advisory lock on an open file. The file is specified by file handle _fildes. Valid operations are given below:

LOCK_SH
Shared lock. More than one process may hold a shared lock for a given file at a given time. However, all locks on DOS/Windows 9X are exclusive locks, so LOCK_SH requests are treated as if they were LOCK_EX requests.

LOCK_EX
Exclusive lock. Only one process may hold an exclusive lock for a given file at a given time.

LOCK_UN
Unlock the file.

LOCK_NB
Don't block when locking. May be specified (by or'ing) along with one of the other operations.

On other systems, a single file may not simultaneously have both shared and exclusive locks. However, on DOS/Windws 9X, all locks are exclusive locks, so this rule is not true for DOS/Windows 9X.

A file is locked, not the file descriptor. So, `dup (2);' does not create multiple instances of a lock.

Dos/Windows 9X do not support shared locks, but the underlying implementation (which uses the F_SETLK (non-blocking) or F_SETLKW (blocking) commands to fcntl, see section fcntl) translates all shared lock request into exclusive lock requests. Thus, requests for shared locks will be treated as if exclusive locks were requested, and only one lock will ever be permitted at any one time on any specified region of the file.

It is therefore wise to code flock by oring LOCK_NB with all lock requests, whether shared or exclusive, and to test the return value to determine if the lock was obtained or not. Using LOCK_NB will cause the implementation to use F_SETLK instead of F_SETLKW, which will return an error if the lock cannot be obtained.

Return Value

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

Portability

ANSI/ISO C No
POSIX 1003.2-1992; 1003.1-2001 (see note 1)

Notes:

  1. 4.4BSD (the flock (2) call first appeared in 4.2BSD).

Example

 
 /* Request a shared lock on file handle fd */
  errno = 0;
  retval = flock(fd, LOCK_SH);

 /* Request a non-blocking shared lock on file handle fd */
  errno = 0;
  retval = flock(fd, LOCK_SH | LOCK_NB);

 /* Request an exclusive lock on file handle fd */
  errno = 0;
  retval = flock(fd, LOCK_EX);

 /* Request a non-blocking exclusive lock on file handle fd */
  errno = 0;
  retval = flock(fd, LOCK_EX | LOCK_NB);

 /* Release a lock on file handle fd */
  errno = 0;
  retval = flock(fd, LOCK_UN);


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright © 2004     Updated Apr 2004