1

我有一个功能可以锁定某个文件夹中的所有文件:

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

所以我称这个函数为:

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

现在似乎找到了文件夹中的所有文件,将它们分配给数组,但由于某种原因,它似乎没有锁定文件。在对其进行测试后(使用 sleep() 并尝试使用其他脚本写入文件),flock()似乎对文件没有任何影响......

任何想法为什么会发生这种情况?

谢谢

4

1 回答 1

1

两件事情:

  • 使用 *nix 锁定文件不是强制性的,只有在所有使用flock()访问的软件都同步的情况下。
  • 该问题是由 PHP 垃圾收集引起的。函数返回后,所有文件都被关闭,因此所有的锁都会自动释放。如果你想让锁保持打开状态,你必须让它们保持打开状态。
于 2012-03-29T14:51:48.950 回答