关于flock文件锁的阻塞与非阻塞
阻塞模式,程序会一直等待。
<?php $fp = fopen("lock.txt", "r"); if(flock($fp,LOCK_EX)) { //code flock($fp,LOCK_UN); } fclose($fp); ?>
非阻塞模式,如果文件被占用直接返回false
<?php $fp = fopen("lock.txt", "r"); if(flock($fp,LOCK_EX | LOCK_NB)) { //code flock($fp,LOCK_UN); } else { echo "error"; } fclose($fp); ?>
阻塞时设置超时时间
if ($fp = fopen($fileName, 'a')) { $startTime = microtime(); do { $canWrite = flock($fp, LOCK_EX); if (!$canWrite) { usleep(round(rand(0, 100) * 1000)); } } while ((!$canWrite) && ((microtime() - $startTime) < 1000)); if ($canWrite) { fwrite($fp, $dataToSave); } fclose($fp); }