<?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中文网其他相关文章!