Share via


_locking

鎖定或解除鎖定檔案的位元組。

語法

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

參數

fd
檔案描述項。

mode
要執行的鎖定動作。

nbytes
要鎖定的位元組數目。

傳回值

如果成功,_locking 會傳回 0。 -1 的傳回值表示失敗,在此情況下 errno 會設定為下列其中一個值。

errno Condition
EACCES 鎖定違規 (檔案已鎖定或解除鎖定)。
EBADF 檔案描述項無效。
EDEADLOCK 鎖定違規。 指定 或 _LK_RLCK 旗標且 _LK_LOCK 在嘗試 10 次之後無法鎖定檔案時傳回。
EINVAL 指定給 _locking 的引數無效。

如果失敗是由於不正確的參數,例如不正確檔案描述元,則會叫用不正確參數處理常式,如參數驗證 中所述

備註

_locking 式會鎖定或解除鎖定 nbytesfd 指定檔案的位元組。 鎖定檔案中的位元組可防止其他處理序存取這些位元組。 所有鎖定或解除鎖定都會從檔案指標的目前位置開始,並繼續進行下一個 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