Header File
io.h, sys\locking.h
Category
Input/output Routines
Prototype
int locking(int handle, int cmd, long length);
Description
Sets or resets file-sharing locks.
locking provides an interface to the operating system file-sharing mechanism. The file to be locked or unlocked is the open file specified by handle. The region to be locked or unlocked starts at the current file position, and is length bytes long.
Locks can be placed on arbitrary, nonoverlapping regions of any file. A program attempting to read or write into a locked region will retry the operation three times. If all three retries fail, the call fails with an error.
The cmd specifies the action to be taken (the values are defined in sys\locking.h):
LK_LOCK |
Lock the region. If the lock is unsuccessful, try once a second for 10 seconds before giving up. |
LK_RLCK |
Same as LK_LOCK. |
LK_NBLCK |
Lock the region. If the lock if unsuccessful, give up immediately. |
LK_NBRLCK |
Same as LK_NBLCK. |
LK_UNLCK |
Unlock the region, which must have been previously locked. |
Return Value
On successful operations, locking returns 0. Otherwise, it returns -1, and the global variable errno is set to one of the following values:
EACCES |
File already locked or unlocked |
EBADF |
Bad file number |
EDEADLOCK |
File cannot be locked after 10 retries (cmd is LK_LOCK or LK_RLCK) |
EINVAL |
Invalid cmd, or SHARE.EXE not loaded |
Example
#include <io.h> #include <fcntl.h> #include <process.h> #include <share.h> #include <stdio.h> #include <sys\locking.h> int main(void) { int handle, status; long length; handle = sopen("c:\\autoexec.bat", O_RDONLY,SH_DENYNO); if (handle < 0) { printf("sopen failed\n"); exit(1); } length = filelength(handle); status = locking(handle,LK_LOCK,length/2); if (status == 0) printf("lock succeeded\n"); else perror("lock failed"); status = locking(handle,LK_UNLCK,length/2); if (status == 0) printf("unlock succeeded\n"); else perror("unlock failed"); close(handle); return 0; }
Portability
POSIX |
Win32 |
ANSI C |
ANSI C++ |
|
+ |
|
|
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
|
What do you think about this topic? Send feedback!
|