php文件读写锁

$file = fopen("test.txt", $fileOpenMode);
flock($file, $lockMode) or die("Can‘t lock");
//...
flock($file, LOCK_UN);
fclose($file);

$fileOpenMode:"r"(读);"r+"(写)(不能用"w",否则由于先打开再加锁,打开后文件内容已经清空了)

$lockMode:LOCK_SH(读);LOCK_EX(写)

<?php
sleep(3);
return;
$mode = $_GET[‘mode‘];
switch($mode){
case "r":
    $fileOpenMode = "r";
    $lockMode = LOCK_SH;
    $sleepTime = 3;
    break;
case "w":
    $fileOpenMode = "r+";
    $lockMode = LOCK_EX;
    $sleepTime = 5;
    break;
}

echo "QueryTime:" . time() . "<br>";
$startTime = time();
echo "Mode:" . $mode . "<br>";
$file = fopen("test.txt", $fileOpenMode);
flock($file, $lockMode) or die("Can‘t lock");
sleep($sleepTime);
switch($mode){
case "r":
    echo "Data:" . fgets($file) . "<br>";
    break;
case "w":
    echo "Data:" . "(Written)" . "<br>";
    fputs($file, "Write data info file at " . time());
    break;
}
flock($file, LOCK_UN);
fclose($file);
echo "Time:" . (time()-$startTime) . "<br>";
echo "Now:" . time() . "<br>";
?>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。