【问题标题】:using flock() on an array of file paths not working在文件路径数组上使用flock()不起作用
【发布时间】:2012-03-29 14:48:12
【问题描述】:

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

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() 似乎对文件没有任何影响......

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

谢谢

【问题讨论】:

    标签: php file-locking flock


    【解决方案1】:

    两件事:

    • 使用 *nix 锁定文件不是强制性的,只有当所有软件使用 flock() 访问同步时。
    • 问题是由 PHPs 垃圾收集引起的。函数返回后,所有文件都被关闭,因此所有的锁都会自动释放。如果您想让锁保持打开状态,就必须让它们保持打开状态。

    【讨论】:

    • 我明白了。那么,当功能完成时,我将如何保持文件打开?谢谢。
    • 例如,您可以返回一个包含文件句柄的数组。在这种情况下,句柄仍然可以通过代码访问,因此不会关闭。
    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2023-04-05
    • 1970-01-01
    • 2021-12-11
    • 2018-11-10
    相关资源
    最近更新 更多