$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>"; ?>