SplFileObject::flock

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

SplFileObject::flockBloqueio de arquivo portável

Descrição

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

Bloqueia ou desbloqueia o arquivo da mesma forma portável que flock().

Parâmetros

operation

operation é uma das seguintes:

  • LOCK_SH para adquirir um bloqueio compartilhado (leitor).
  • LOCK_EX para adquirir um bloqueio exclusivo (escritor).
  • LOCK_UN para liberar um bloqueio (compartilhado ou exclusivo).

Também é possível adicionar LOCK_NB como um bitmask para uma das operações acima, se flock() não deve bloquear durante a tentativa de bloqueio.

wouldBlock

Definido como true se o bloqueio bloqueasse (condição de errno EWOULDBLOCK).

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Exemplo de SplFileObject::flock()

<?php
$file
= new SplFileObject("/tmp/lock.txt", "w");
if (
$file->flock(LOCK_EX)) { // do an exclusive lock
$file->ftruncate(0); // truncate file
$file->fwrite("Write something here\n");
$file->flock(LOCK_UN); // release the lock
} else {
echo
"Couldn't get the lock!";
}
?>

Veja Também

  • flock() - Travamento consultivo portável de arquivo

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