lock or unlock part of a file
#include <sys/locking.h>
int locking( int filedes, int mode,
long nbyte );
int _locking( int filedes, int mode,
long nbyte );
The locking() function locks or unlocks nbyte bytes of the file specified by filedes. The file must be opened with write access to lock it.
![]() |
Locking is a protocol designed for updating a file shared among
concurrently running applications.
Locks are only advisory, that is, they don't 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.
Locks are ignored by the following functions:
|
The locking and unlocking takes place at the current file position. The argument mode specifies the action to be performed. The possible values are:
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.
The _locking() function is identical to locking(). Use _locking() for ANSI/ISO naming conventions.
#include <stdio.h>
#include <sys/locking.h>
#include <share.h>
#include <fcntl.h>
#include <unistd.h>
void main()
{
int filedes ;
unsigned nbytes;
unsigned long offset;
char buffer[512];
nbytes = 512;
offset = 1024;
filedes = sopen( "db.fil", O_RDWR, SH_DENYNO );
if( filedes != -1 ) {
lseek( filedes , offset, SEEK_SET );
locking( filedes , LK_LOCK, nbytes );
read( filedes , buffer, nbytes );
/* update data in the buffer */
lseek( filedes , offset, SEEK_SET );
write( filedes , buffer, nbytes );
lseek( filedes , offset, SEEK_SET );
locking( filedes , LK_UNLCK, nbytes );
close( filedes );
}
}
WATCOM
_locking() conforms to ANSI/ISO naming conventions.
| Safety: | |
|---|---|
| Interrupt handler | No |
| Signal handler | No |
| Thread | Yes |
creat(), errno, fcntl(), lock(), open(), sopen(), unlock()