时间:2021-07-01 10:21:17 帮助过:35人阅读
代码如下:
// Lock a file, timing out if it takes too long.
function lock ($lock, $tries) {
$lock0 = ".{$lock}0";
$lock1 = ".{$lock}1";
for ($i=0; $i<$tries; $i++) {
if (!is_file($lock0)) {
touch($lock0);
if (!is_file($lock1)) {
touch($lock1);
return 1;
}
}
usleep(100);
}
return 0;
}
// Unlock a file.
function unlock ($lock) {
unlink(".{$lock}1");
unlink(".{$lock}0");
}
// Usage example.
$filename = "somefile";
$data = "stuff and thingsn";
$tries = 10;
if (lock($filename, $tries)) {
$h = fopen($filename, "a") or die();
fwrite($h, $data);
fclose($h);
/**
* 另外一个进程写文件,检查是否锁定
*/
if (lock($filename, $tries)) {
$h2 = fopen($filename, "a") or die();
fwrite($h2,'check lock');
fclose($h2);
}else{
//die("Failed to lock $filename after ".($tries*100)." milliseconds!";
}
unlock($filename);
} else {
//die("Failed to lock $filename after ".($tries*100)." milliseconds!";
}
?>
以上就介绍了flock 模拟flock实现文件锁定,包括了flock方面的内容,希望对PHP教程有兴趣的朋友有所帮助。