ID Number: Q79066
6.00 6.00a 6.00ax | 6.00 6.00a
MS-DOS | OS/2
docerr
Summary:
SYMPTOMS
The program example for locking(), LOCKING.C, on page 457 of the
"Microsoft C Run-Time Library Reference" for Microsoft C version
6.0 is incorrect. The first call to locking() locks the first 30
bytes of the file. The program then reads the 30 bytes. The second
call to locking() should unlock them when that the program is done
with them. However, the file pointer is not reset before the second
call. Since all locking and unlocking begins at the current
position of the file pointer, the unlock fails and -1 is returned.
In addition, pos and result are unreferenced variables.
RESOLUTION
The locking() failure can be avoided by using lseek() to reposition
the file pointer before attempting to unlock the bytes.
More Information:
The following sample program is an updated version of LOCKING.C. The
line added is indicated.
Sample Code
-----------
/* Compile options needed: none
*/
/* LOCKING.C: This program opens a file with sharing. It locks some
* bytes before reading them, then unlocks them. Note that the program
* works correctly only if the following conditions are met:
* - The file exists.
* - The program is run under OS/2, under DOS 3.0 or later
* with file sharing installed (SHARE.COM or SHARE.EXE), or
* if a Microsoft networks-compatible network is running.
*/
#include <io.h>
#include <sys\types.h>
#include <sys\stat.h>
#include <sys\locking.h>
#include <share.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
void main()
{
int fh, numread;
long pos, result;
char buffer[40];
/* Quit if can't open file or DOS version doesn't support sharing. */
fh = sopen( "locking.c", O_RDWR, SH_DENYNO, S_IREAD | S_IWRITE );
if( (fh == -1) || (_osmajor < 3) )
exit( 1 );
/* Lock some bytes and read them. Then unlock. */
if( locking( fh, LK_NBLCK, 30L ) != -1 )
{
printf( "No one can change these bytes while I'm reading them.\n" );
numread = read( fh, buffer, 30 );
printf( "%d bytes read: %.30s\n", numread, buffer );
/******** line added here ********/
lseek( fh, 0L, SEEK_SET );
/*************************************/
locking( fh, LK_UNLCK, 30L );
printf( "Now I'm done. Do what you will with them.\n" );
}
else
perror( "Locking failed\n" );
close( fh );
}
Additional reference words: 6.00 6.00a 6.00ax