我需要锁定文件,读取数据,写入文件,然后关闭它。我遇到的问题是我正在尝试为fopen找到正确的模式。
With 'a+‘-始终附加数据,with 'w+’打开时截断所有数据,with '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);发布于 2011-04-16 06:17:16
您需要'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);
}发布于 2011-04-16 06:22:01
我相信你想要c+。这与r+类似,不同之处在于它将创建一个不存在的文件。如果你不想这样做,那就改用r+。打开文件后,根据需要使用flock()。你也可以通过c+打开来读写。除此之外,我认为您可以使用相同的代码。
另一个答案是正确的,但他们使用了一个额外的步骤来确定使用r还是w,而c将自动执行此操作。
发布于 2011-04-16 06:33:11
弗兰克·法默的代码并不比你的好。在file_exists和fopen之间,其他进程可以对文件进行自己的操作。
在打开'task‘文件之前创建semaphore-file。
类似于:
if (($f_sem = @fopen($task_file.'.sem', 'x')))
{
//your code (with flock)
fclose($f_sem);
unlink($task_file.'.sem');
}https://stackoverflow.com/questions/5682616
复制相似问题