using flock() on an array of file paths not working
-
27-05-2021 - |
Pregunta
I have a function that locks all files in a certain folder:
function lockFolder_files($folder='',$task=''){
global $file_array;//I need to use this var outside the function too
$file_array=glob($folder . '*_che.php');//this lists all files ending with "_che.php" in the array from folder1.
//now do a foreach on the array and open the file, and lock it:
foreach($file_array as $path){
$lock=fopen($path,"a+")//open with append mode
if($task=="lock"){
flock($lock,LOCK_EX);
}
elseif($task=="unlock"){
flock($lock,LOCK_UN);
}
}//end of foreach
if(count($file_array)==0){echo"no files were found in the folder"; return false;}
}//end of function
So I call this function :
lockFolder_files("blah1/blah/myfolder","lock");
//do what i need to do with the array of files locked ($file_array)
lockFolder_files("blah1/blah/myfolder","unlock");//unlock all the files
Now it seems to find all the files in the folder, assign them to the array, but for some reason, it doesn't seem to lock the files. After testing it (using sleep() and attempting to write to the file with other scripts) the flock()
seems to be having no effect on the files what so ever....
Any ideas why this is happening?
Thanks
Solución
Two things:
- file locking with *nix is not mandatory, only if all software uses
flock()
access is synchronized. - The problem is caused by PHPs garbage collection. After the function returns, all files are closed and therefore all locks are released automatically. You have to keep them open if you want the locks to stay.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow