Home > Article > Backend Development > Detailed explanation of the function of locking files using flock in PHP
<?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); ?>
For example: Please write a piece of PHP code to ensure that multiple processes write the same file successfully at the same time
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; }
The above is the detailed content of Detailed explanation of the function of locking files using flock in PHP. For more information, please follow other related articles on the PHP Chinese website!