CakeFest 2024: The Official CakePHP Conference

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 для снятия блокировки (разделяемой или эксклюзивной).

Флаг LOCK_NB добавляют как битовую маску к одной операции из списка выше, если функция flock() не должна блокироваться во время попытки блокировки файла.

wouldBlock

Получает значение true, если блокировка будет блокирующей (в переменную errno будет записан код ошибки EWOULDBLOCK).

Возвращаемые значения

Возвращает 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