Fungsi flock
Fungsi flock meletakkan atau mengangkat penyekat fail. Parameter pertamanya menerima penunjuk fail yang diperoleh melalui fopen, parameter kedua - jenis penyekat (LOCK_SH, LOCK_EX atau LOCK_UN), dan parameter ketiga yang pilihan - bendera untuk operasi tidak menyekat.
Sintaks
flock(resource $handle, int $operation, int &$would_block = null): bool
Contoh
Menyekat fail untuk akses eksklusif (penulisan):
<?php
$file = fopen("data.txt", "c+");
if (flock($file, LOCK_EX)) {
ftruncate($file, 0);
fwrite($file, "Data baharu");
flock($file, LOCK_UN);
}
fclose($file);
?>
Contoh
Penyekat dikongsi untuk pembacaan:
<?php
$file = fopen("data.txt", "r");
if (flock($file, LOCK_SH)) {
$content = fread($file, filesize("data.txt"));
flock($file, LOCK_UN);
}
fclose($file);
echo $content;
?>
Contoh
Cubaan untuk mendapatkan penyekat tanpa menyekat:
<?php
$file = fopen("data.txt", "c+");
if (flock($file, LOCK_EX | LOCK_NB, $would_block)) {
if ($would_block) {
echo "Fail disekat oleh proses lain";
} else {
fwrite($file, "Data");
flock($file, LOCK_UN);
}
}
fclose($file);
?>
Lihat juga
-
fungsi
fopen,
yang membuka fail -
fungsi
fclose,
yang menutup fail -
fungsi
is_writable,
yang menyemak kebolehan untuk menulis