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.
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
SplFileObject::flock — Портируемая блокировка файла
$operation
, int &$wouldBlock
= null
): boolБлокирует или разблокирует файл тем же портируемым способом, что и flock().
operation
operation
может принимать следующие значения:
LOCK_SH
для получения разделяемой блокировки (чтение).
LOCK_EX
для получения эксклюзивной блокировки (запись).
LOCK_UN
для снятия блокировки (разделяемой или эксклюзивной).
Также возможно добавить LOCK_NB
в качестве битовой маски к одной
из вышеуказанных операций, если flock() не должен
блокироваться во время попытки блокировки.
wouldBlock
Будет установлен true
, если блокировка будет блокирующей (код ошибки 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 "Не удалось получить блокировку!";
}
?>
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.
@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