我需要锁定文件,读取数据,写入文件然后关闭它.我遇到的问题是我正在尝试为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);
Run Code Online (Sandbox Code Playgroud)
您想要'r+'(或者c+如果您使用的是较新版本的PHP). 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);
}
Run Code Online (Sandbox Code Playgroud)