<?php $file = fopen("test.txt","w+"); if (flock($file,LOCK_EX)) { fwrite($file,"Write something"); flock($file,LOCK_UN); } else { echo "Error locking file!"; } fclose($file); ?>
#例如:請寫一段PHP程式碼,確保多個行程同時寫入同一個檔案成功
#
function writeData($path, $mode,$data) { $fp = fopen($path, $mode); $retries = 0; $max_retries = 100; do{ if ($retries > 0) { usleep(rand(1, 10000)); } $retries += 1; }while (!flock($fp, LOCK_EX) and $retries<= $max_retries); if ($retries == $max_retries) { return false; } fwrite($fp, "$data\n"); flock($fp, LOCK_UN); fclose($fp); return true; }
以上是PHP利用flock實作在檔案上加鎖的功能詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!