_locking

ファイルのバイトをロックまたはロック解除します。

構文

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

パラメーター

fd
ファイル記述子。

mode
実行するロック アクション。

nbytes
ロックするバイト数。

戻り値

処理が正常に終了した場合、_locking は 0 を返します。 戻り値 -1 は失敗を示し、その場合 errno は次のいずれかの値に設定されます。

errno 状態
EACCES ロック違反 (ファイルはすでにロックされている場合もロック解除されている場合もある)。
EBADF 無効なファイル記述子。
EDEADLOCK ロック違反。 or _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 は隣接する領域をマージしません。2 つのロックされたリージョンが隣接している場合は、各リージョンを個別にロック解除する必要があります。 領域は短期間だけロックされ、ファイルを閉じる前またはプログラムを終了する前にはロックを解除する必要があります。

既定では、この関数のグローバル状態の適用対象は、アプリケーションになります。 この動作を変更するには、「CRT のグローバル状態」を参照してください

必要条件

ルーチンによって返される値 必須ヘッダー オプション ヘッダー
_locking <io.h> と <sys/locking.h> <errno.h>

互換性の詳細については、「 Compatibility」を参照してください。

ライブラリ

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