SplFileObject::flock

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::flock簡易なファイルロックを行う

説明

public SplFileObject::flock(int $operation, int &$wouldBlock = null): bool

flock() と同じ簡易な方法でファイルをロックもしくはロック解除する。

パラメータ

operation

operation は次のいずれかです:

  • 共有ロック (読み手) にするには LOCK_SH
  • 排他ロック (書き手) にするには LOCK_EX
  • (共有もしくは排他) ロックを解除するには LOCK_UN

ロックを試みている間に flock() がブロックすべきでない場合は、上の操作のいずれかに LOCK_NB をビットマスクとして追加できます。

wouldBlock

ロックがブロックされる場合 (errno が EWOULDBLOCK である)、true にセットします。

戻り値

成功した場合に true を、失敗した場合に false を返します。

例1 SplFileObject::flock() の例

<?php
$file
= new SplFileObject("/tmp/lock.txt", "w");
if (
$file->flock(LOCK_EX)) { // 排他ロックを行う
$file->ftruncate(0); // ファイルを丸める
$file->fwrite("ここで何かを書き出します\n");
$file->flock(LOCK_UN); // ロックを解除する
} else {
echo
"ロックを取得できませんでした!";
}
?>

参考

  • flock() - 汎用のファイルロックを行う

add a note

User Contributed Notes 2 notes

up
4
digitalprecision at gmail dot com
13 years ago
For the record, the example given here has an explicit command to truncate the file, however with a 'write mode' of 'w', it will do this for you automatically, so the truncate call is not needed.
up
0
Ahmed Rain
1 year ago
@digitalprecision What you said is not completely true, ftruncate(0); is needed if there was a write to the file before the lock is acquired. You also may need fseek(0); to move back the file pointer to the beginning of the file

<?php
$file
= new SplFileObject("/tmp/lock.txt", "w");
$file->fwrite("xxxxx"); // write something before the lock is acquired
sleep(5); // wait for 5 seconds

if ($file->flock(LOCK_EX)) { // do an exclusive lock
$file->fwrite("Write something here\n");
$file->flock(LOCK_UN); // release the lock
} else {
echo
"Couldn't get the lock!";
}
?>

"lock.txt" content:

xxxxxWrite something here
To Top