_locking

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

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

パラメーター

  • fd
    ファイル記述子。

  • モード
    実行するロック動作。

  • nBytes
    ロック対象のバイト数。

戻り値

正常終了した場合、_locking は 0 を返します。 エラーが発生した場合は -1 を返し、グローバル変数 errno に次の値のいずれかが設定されます。

  • EACCES
    ロック違反 (ファイルが既にロックされているかロック解除されている)。

  • EBADF
    ファイル記述子が無効。

  • EDEADLOCK
    ロック違反。 _LK_LOCK フラグまたは _LK_RLCK フラグが指定して 10 回試行してもファイルをロックできない場合に返されます。

  • EINVAL
    _locking 関数に指定した引数が無効。

エラーの原因が、無効なファイル記述子などの不適切なパラメーターによるものである場合は、「パラメーターの検証」に説明されているように、無効なパラメーター ハンドラーが呼び出されます。

解説

_locking 関数は、fd で指定されたファイル内の nbytes バイトをロック、またはロック解除します。 ファイル内のバイト範囲をロックすると、ほかのプロセスはそれらのバイト範囲にアクセスできなくなります。 ロックまたはロック解除の対象は、ファイル ポインターの現在位置から、それ以降の nbytes バイトです。 ファイルの終端以降のバイト列もロックできます。

mode では、Locking.h で定義されている次のマニフェスト定数のいずれかを指定します。

  • _LK_LOCK
    指定されているバイト列をロックする。 ロックできない場合は、1 秒後に再試行します。 10 回試行してもロックできない場合は、エラーを返します。

  • _LK_NBLCK
    指定されているバイト列をロックする。 ロックできない場合は、エラーを返します。

  • _LK_NBRLCK
    _LK_NBLCK と同じ。

  • _LK_RLCK
    _LK_LOCK と同じ。

  • _LK_UNLCK
    指定されているバイト列のロックを解除する。既にロックされているバイト列にしか適用されません。

ファイル内の重なり合っていない複数の領域をロックできます。 ロックを解除する領域は、既にロックされていた領域だけです。 _locking 関数は隣接する領域をマージしません。ロックされている 2 つの領域が隣接している場合は、それぞれの領域のロックを個別に解除する必要があります。 領域は長時間ロックしないでください。ファイルを閉じるかプログラムを終了する前に、ロックを解除してください。

必要条件

ルーチン

必須ヘッダー

オプション ヘッダー

_locking

<io.h> および <sys/locking.h>

<errno.h>

互換性の詳細については、「C ランタイム ライブラリ」の「互換性」を参照してください。

ライブラリ

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

同等の .NET Framework 関数

System::IO::FileStream::Lock

参照

参照

ファイル処理

_creat、_wcreat

_open、_wopen