请问可以在数个线程中同时对一个文件使用open()函数和read()函数吗?
请问可以在不同线程中同时对一个文件使用open()函数和read()函数吗?
比如:
//Thread1:
int a = open("c:/1.txt",O_RDONLY);
//Thread2:
int a = open("c:/1.txt",O_RDONLY);
int main()
{
int a = open("c:/1.txt",O_RDONLY);
}
//Thread1:
read(a,ptr,100);
//Thread2:
read(a,ptr,100);
mode must be one of the following manifest constants, which are defined in LOCKING.H:
_LK_LOCK
Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked, the constant returns an error.
_LK_NBLCK
Locks the specified bytes. If the bytes cannot be locked, the constant returns an error.
_LK_NBRLCK
Same as _LK_NBLCK.
_LK_RLCK
Same as _LK_LOCK.
_LK_UNLCK
Unlocks the specified bytes, which must have been previously locked.
Multiple regions of a file that do not overlap can be locked. A region being unlocked must have been previously locked. _locking does not merge adjacent regions; if two locked regions are adjacent, each region must be unlocked separately. Regions should be locked only briefly and should be unlocked before closing a file or exiting the program.
Example
/* 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 file exists.
*/
#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( void )
{
int fh, numread;
char buffer[40];
/* Quit if can't open file or system doesn't
* support sharing.
*/
fh = _sopen( "locking.c", _O_RDWR, _SH_DENYNO,
_S_IREAD
[解决办法]
_S_IWRITE );
if( fh == -1 )
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 );
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 );
}
Output
No one can change these bytes while I'm reading them
30 bytes read: /* LOCKING.C: This program ope
Now I'm done. Do what you will with them
File Handling Routines
See Also _creat, _open
[解决办法]
可以的,但偏移量是各自fd的。