block - Lock files in PHP without using flock -
when user upload file(users can upload multiple files)
exec('nohup php /main/apache2/work/upload/run.php &');
i using nohup
needs executed in end.
in original design run.php
scans directory using scandir
everytime it's executed. exclusive lock lock_ex
on file using flock
, use lock_nb
skip file if has lock , go next one. if file has lock //do logic
. problem server missing fcntl()
library , since flock
uses library execute locking mechanism, flock
won't work @ moment. it's going take month or 2 installed(i have no control on that).
so work around have temporary file lock.txt acts lock. if filename exists in lock.txt skip file , go next one.
$dir = "/main/apache2/work/upload/files/"; $files = scandir($dir); $filename = "lock.txt"; for($i=0; $i<count($files); $i++) { if(substr(strrchr($files[$i],'.csv'),-4) == '.csv') { if($file_handle = fopen("$filename", "rb")) { while(!feof($file_handle)) { $line = fgets($file_handle); $line = rtrim($line); if($line == "") { break; } else { if($files[$i] == $line) { echo "reading lock: ".$line."</br>"; $i++; //go next file } } } fclose($file_handle); } if($i >= count($files)) { die("$i end of file"); } if($file_handle = fopen("$filename", "a+")) { if(is_writable($filename)) { $write = fputs($file_handle, "$files[$i]"."\n"); //do logic //delete file name - stuck here fclose($file_handle); } } } else { //do nothing } }
how can delete filename lock.txt
?
more importantly, there better way lock file in php without using flock
?
having shared lock database moves locking problem file; doesn't solve it.
a better solution use 1 lock file per real file. if want lock access myfile.csv
check file_exists('myfile.csv.lock')
, touch('myfile.csv.lock')
if doesn't exist. , unlink('myfile.csv.lock')
when done.
now, there possible race-condition between file_exists() , touch(), can mitigated storing pid in file , checking if getmypid()
indeed process holding lock.
Comments
Post a Comment