[Previous]
[Contents]
[Next]

lock()

lock data in a file

Synopsis:

#include <unistd.h>
int lock( int filedes,
          unsigned long offset,
          unsigned long nbytes );

Description:

The lock() function locks nbytes amount of data in the file designated by filedes, starting at byte offset in the file. The file must be opened with write access to lock it.


Note: Locking is a protocol designed for updating a file shared among concurrently running applications. Locks are only advisory, that is, they do not prevent an errant or poorly-designed application from overwriting a locked region of a shared file. An application should use locks to indicate regions of a file that are to be updated by the application, and it should respect the locks of other applications.

Advisory locks are ignored by the following functions:

  • chsize()
  • ltrunc()
  • open()
  • read()
  • sopen()
  • write()

Multiple regions of a file can be locked, but no overlapping regions are allowed. You cannot unlock multiple regions in the same call, even if the regions are contiguous. All locked regions of a file should be unlocked before closing a file or exiting the program.

Returns:

0
Success
-1
An error occurred. errno is set to indicate the error.

Examples:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

void main()
  {
    int filedes ;
    char buffer[20];

    filedes = open( "file", O_RDWR );
    if( filedes != -1 ) {
      if( lock( filedes , 0L, 20L ) ) {
        printf( "Lock failed\n" );
      } else {
        read( filedes , buffer, 20 );

        /* update the buffer here */

        lseek( filedes , 0L, SEEK_SET );
        write( filedes , buffer, 20 );
        unlock( filedes , 0L, 20L );
      }
      close( filedes );
    }
  }

Classification:

WATCOM

Safety:
Interrupt handler No
Signal handler No
Thread Yes

See also:

errno, fcntl(), locking(), open(), sopen(), unlock()


[Previous]
[Contents]
[Next]