我需要锁定文件、读取数据、写入文件然后关闭它。我遇到的问题是我正在尝试为 fopen 找到正确的模式。
使用 'a+' - 始终附加数据,使用 'w+' 在打开时截断所有数据,使用 'x+' - 无法锁定文件。
这是我的代码:
$fh_task = fopen($task_file, 'w+');
flock($fh_task, LOCK_EX) or die('Cant lock '.$task_file);
$opt_line = '';
while(!feof($fh_task)){
$opt_line .= fread($fh_task, 4096);
}
$options = unserialize($opt_line);
$options['procceed']++;
rewind($fh_task);
fwrite($fh_task, serialize($options));
flock($fh_task, LOCK_UN);
fclose($fh_task);
最佳答案
您需要 'r+'
(如果您使用的是较新版本的 PHP,则需要 c+
)。 r+
不会截断(c+
也不会),但仍然允许您编写。
这是我上次使用这些函数时的摘录:
/*
if file exists, open in read+ plus mode so we can try to lock it
-- opening in w+ would truncate the file *before* we could get a lock!
*/
if(version_compare(PHP_VERSION, '5.2.6') >= 0) {
$mode = 'c+';
} else {
//'c+' would be the ideal $mode to use, but that's only
//available in PHP >=5.2.6
$mode = file_exists($file) ? 'r+' : 'w+';
//there's a small chance of a race condition here
// -- two processes could end up opening the file with 'w+'
}
//open file
if($handle = @fopen($file, $mode)) {
//get write lock
flock($handle,LOCK_EX);
//write data
fwrite($handle, $myData);
//truncate all data in file following the data we just wrote
ftruncate($handle,ftell($handle));
//release write lock -- fclose does this automatically
//but only in PHP <= 5.3.2
flock($handle,LOCK_UN);
//close file
fclose($handle);
}
关于php - 打开,恐惧和蜂拥而至,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682616/