_locking

锁定或解锁文件的字节。

语法

int _locking(
   int fd,
   int mode,
   long nbytes
);

参数

fd
文件描述符。

mode
要执行的锁定操作

nbytes
要锁定的字节数。

返回值

如果成功,则 _locking 返回 0。 返回值 -1 表示失败,在这种情况下,errno 会设为以下值之一。

errno 条件
EACCES 锁定冲突(文件已锁定或已解锁)。
EBADF 无效的文件描述符。
EDEADLOCK 锁定冲突。 返回条件是:指定了 _LK_LOCK_LK_RLCK 标志且该文件在尝试 10 次后仍无法锁定。
EINVAL 一个无效参数将提供给 _locking

如果失败是由错误参数导致,如无效的文件描述符,则会调用无效的参数处理程序,如参数验证中所述。

备注

_locking 函数会锁定或解锁由 fd 指定的文件的 nbytes 字节。 锁定文件中的字节将阻止其他进程访问这些字节。 所有锁定或解锁在文件指针的当前位置开始,并继续到接下来的 nbytes 字节。 可能会锁定超出文件末尾的字节。

mode 必须是 Locking.h 中定义的以下清单常数之一。

mode 效果
_LK_LOCK 锁定指定字节。 如果无法锁定字节,该程序会立即在 1 秒后再次尝试。 如果在 10 次尝试后无法锁定字节,该常数将返回错误。
_LK_NBLCK 锁定指定字节。 如果无法锁定字节,该常数将返回错误。
_LK_NBRLCK _LK_NBLCK 相同。
_LK_RLCK _LK_LOCK 相同。
_LK_UNLCK 要解锁的指定字节必须在之前锁定过。

可以锁定文件中不重叠的多个区域。 正在解锁的区域必须在之前锁定过。 _locking 不会合并相邻区域,如果有两个相邻的锁定区域,每个区域必须单独解锁。 区域应只是暂时锁定,在关闭文件或退出程序前应进行解锁。

默认情况下,此函数的全局状态范围限定为应用程序。 要更改此行为,请参阅 CRT 中的全局状态

要求

例程 必需的标头 可选标头
_locking <io.h> 和 <sys/locking.h> <errno.h>

有关兼容性的详细信息,请参阅 兼容性

C 运行时库的所有版本。

示例

// crt_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 <sys/types.h>
#include <sys/stat.h>
#include <sys/locking.h>
#include <share.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <io.h>

int main( void )
{
   int  fh, numread;
   char buffer[40];

   /* Quit if can't open file or system doesn't
    * support sharing.
    */
   errno_t err = _sopen_s( &fh, "crt_locking.txt", _O_RDONLY, _SH_DENYNO,
                          _S_IREAD | _S_IWRITE );
   printf( "%d %d\n", err, fh );
   if( err != 0 )
      exit( 1 );

   /* Lock some bytes and read them. Then unlock. */
   if( _locking( fh, LK_NBLCK, 30L ) != -1 )
   {
      long lseek_ret;
      printf( "No one can change these bytes while I'm reading them\n" );
      numread = _read( fh, buffer, 30 );
      buffer[30] = '\0';
      printf( "%d bytes read: %.30s\n", numread, buffer );
      lseek_ret = _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 );
}

输入:crt_locking.txt

The first thirty bytes of this file will be locked.

示例输出

No one can change these bytes while I'm reading them
30 bytes read: The first thirty bytes of this
Now I'm done. Do what you will with them

另请参阅

文件处理
_creat_wcreat
_open_wopen