PHP 8.1.28 Released!

SplFileObject::flock

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

SplFileObject::flockBloqueo de ficheros portable

Descripción

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

Bloquea o desbloquea el fichero de la misma manera portable que flock().

Parámetros

operation

operation es una operación de las siguientes:

  • LOCK_SH para adquirir un bloqueo compartido (lectura).
  • LOCK_EX para adquirir un bloqueo exclusivo (escritura).
  • LOCK_UN para liberar un bloqueo (compartido o exclusivo).

También es posible añadir LOCK_NB como máscara de bits a una de las operaciones anteriores, si flock() no debe bloquearse durante el intento de bloqueo.

wouldBlock

Establecer a true si el bloqueo hará que la función quede esperando (condición de errno EWOULDBLOCK).

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de SplFileObject::flock()

<?php
$file
= new SplFileObject("/tmp/bloqueado.txt", "w");
if (
$file->flock(LOCK_EX)) { // adquirir un bloqueo exclusivo
$file->ftruncate(0); // truncar el fichero
$file->fwrite("Escribir alguna cosa\n");
$file->flock(LOCK_UN); // liberar el bloqueo
} else {
echo
"¡No se pudo obtener el bloqueo!";
}
?>

Ver también

  • flock() - Bloqueo de ficheros recomendado y portable

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