Fungsi flock
Fungsi flock mengatur atau melepas penguncian file. Parameter pertamanya menerima pointer ke file, yang diperoleh melalui fopen, parameter kedua - jenis penguncian (LOCK_SH, LOCK_EX atau LOCK_UN), dan parameter ketiga yang opsional - flag untuk operasi non-blocking.
Sintaks
flock(resource $handle, int $operation, int &$would_block = null): bool
Contoh
Mengunci file untuk akses eksklusif (penulisan):
<?php
$file = fopen("data.txt", "c+");
if (flock($file, LOCK_EX)) {
ftruncate($file, 0);
fwrite($file, "Data baru");
flock($file, LOCK_UN);
}
fclose($file);
?>
Contoh
Penguncian bersama untuk membaca:
<?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
Upaya non-blocking untuk mendapatkan kunci:
<?php
$file = fopen("data.txt", "c+");
if (flock($file, LOCK_EX | LOCK_NB, $would_block)) {
if ($would_block) {
echo "File sedang dikunci oleh proses lain";
} else {
fwrite($file, "Data");
flock($file, LOCK_UN);
}
}
fclose($file);
?>
Lihat juga
-
fungsi
fopen,
yang membuka file -
fungsi
fclose,
yang menutup file -
fungsi
is_writable,
yang memeriksa kemungkinan penulisan